首页 > 解决方案 > 迭代多级哈希

问题描述

我正在将 CSV 文件读入多级哈希。我正在尝试遍历哈希。

这是加载哈希的代码。有用。如果我使用 Dumper 打印它,我有我所期望的。

use Data::Dumper;


my $connectionsinfile = "switchconnections.csv";
my %switchportinfo;

open (my $INFILE,'<',$connectionsinfile) or die "Couldn't open SVC input file $connectionsinfile\n$!";
my @recs = <$INFILE>;
close $INFILE;
chomp @recs;

  use constant { true => 1, false => 0};
   my @header = split',', $recs[0];

# now that we have the header, remove it from the array
  shift @recs;
foreach my $rec (@recs) {
        
        my @data = split(',',$rec);
        @row_data{@header} = @data;
        my $switchname = $row_data{'Switch Name'};
    my $switchport = $row_data{'Port'};
        $switchportinfo{$switchname}{$switchport} = {%row_data};
}

此代码有效,除了它打印外键和内键,然后为内键打印“HASH(XXXXXX)”值

for $key (keys %switchportinfo) 
{
    print "$key: \n";
    for $ele (keys %{$switchportinfo{$key}})
    {   
        
        print "  $ele: " . $switchportinfo{$key}->{$ele} . "\n";
    }
}

此代码导致错误“在 test2.pl 中,键的 arg 1 类型必须是散列或数组(不是键/值散列切片)”}

我希望能够打印内部哈希值。

for $key (keys %switchportinfo) 
{
    print "$key: \n";
    for $ele (keys %{$switchportinfo{$key}})
    {   
        print "$ele: \n";
        for $ele2 (keys %{switchportinfo{$key}{$ele}}) {
         print "   $ele2:  " . $switchportinfo{$key}{$ele}->{$ele2}. "\n";
        }
       
    }
}

标签: perl

解决方案


你缺少一个$in %{switchportinfo{$key}{$ele}}。总是使用use strict; use warnings;.

最后一个片段是正确的。但是让我们使用更好的名称,例如第一个片段中使用的名称。

for my $switchname (keys %switchportinfo) 
{
   print "switchname: $switchname\n";
   for my $switchport (keys %{ $switchportinfo{$switchname} })
   {   
      print "   switchport: $switchport\n";
      for my $header (keys %{ $switchportinfo{$switchname}{$switchport} }) {
         print "     $header: $switchportinfo{$switchname}{$switchport}{$header}\n";
      }
   }
}

推荐阅读