为什么我的多层哈希打印方式与我期望的一样?

时间:2011-05-04 15:34:41

标签: perl hash hash-of-hashes

这是代码,它不起作用,我想要做的是将Hash of Hashes传递给子程序aka函数,但它给出了一些奇怪的输出。

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";
         foreach 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)   

3 个答案:

答案 0 :(得分:8)

perlcritic可以成为调试Perl代码的便捷工具:

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)

这是一种发现其他人所说内容的自动方式:print是一种内置功能。<​​/ p>

答案 1 :(得分:4)

print是内置函数;要调用名为的子例程,请使用&print(...)而不是print(...)

答案 2 :(得分:3)

我认为您的问题是您正在调用print子程序,并且已经在perl中定义了print。

尝试更改地图的名称,例如,这对我有用:

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";
    }
                 }
}