Why does my multi-leveled hash print the way I expect?
Here's the code and its not working, What I am trying to do is to pass Hash of Hashes to subroutine aka function, but it gives some odd output.
my %file_attachments = (
'test1.zip' => { 'price' => '10.00', 'desc' => 'the 1st test'},
'test2.zip' => { 'price' => '12.00', 'desc' => 'the 2nd test'},
'test3.zip' => { 'price' => '13.00', 'desc' => 'the 3rd test'},
'test4.zip' => { 'price' => '14.00', 'desc' => 'the 4th test'}
);
my $a="test5.zip";
my $b="the 5th test";
$file_attachments{$a}->{'price'} = '18.00';
$file_attachments{$a}->{'desc'} =$b;
print(%file_attachments);
sub print{
my %file =@_;
foreach my $line (keys %file) {
print "$line: \n";
for开发者_如何学运维each my $elem (keys %{$file{$line}}) {
print " $elem: " . $file{$line}->{$elem} . "\n";
}
}
OUTPUT::::
test2.zipHASH(0x3a9c6c)test5.zipHASH(0x1c8b17c)test3.zipHASH(0x1c8b3dc)test1.zipHASH(0x3a9b1c)test4.zipHASH(0x1c8b5dc)
perlcritic can be a handy tool in debugging Perl code:
perlcritic -1 my_code.pl
Subroutine name is a homonym for builtin function at line 24, column 1. See page 177 of PBP. (Severity: 4)
This is an automated way of discovering what others have stated: that print
is a built-in function.
print
is a builtin function; to call a subroutine named that, use &print(...)
instead of print(...)
.
I think your problem is that you are calling print
to your subroutine, and print is already defined in perl.
Try changing the name of the subrutine, for instance, this works for me:
my %file_attachments = (
'test1.zip' => { 'price' => '10.00', 'desc' => 'the 1st test'},
'test2.zip' => { 'price' => '12.00', 'desc' => 'the 2nd test'},
'test3.zip' => { 'price' => '13.00', 'desc' => 'the 3rd test'},
'test4.zip' => { 'price' => '14.00', 'desc' => 'the 4th test'}
);
my $a="test5.zip";
my $b="the 5th test";
$file_attachments{$a}->{'price'} = '18.00';
$file_attachments{$a}->{'desc'} =$b;
printtest(%file_attachments);
sub printtest{
my %file =@_;
foreach my $line (keys %file) {
print "$line: \n";
foreach my $elem (keys %{$file{$line}}) {
print " $elem: " . $file{$line}->{$elem} . "\n";
}
}
}
精彩评论