perl - 迭代多级哈希
问题描述
我正在将 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";
}
}
}
解决方案
你缺少一个$
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";
}
}
}
推荐阅读
- javascript - nodejs中的语法babel
- google-apps-script - 在新标签页中从脚本打开另一个 google 工作表
- angular - 如何将字符串从 angular 6 发送到 springboot 休息控制器?
- google-tag-manager - 使用 Google 跟踪代码管理器查找和替换页面文本字符串
- kubernetes - Kubernetes etcd 没有出现
- gcc - F2PY 使用 PRINT 给出未解决的外部错误
- documentum - Excel 中的 DQL 结果
- java - 二维目标拦截算法
- javascript - 抑制 onChange 触发反应
- docker - 如何在 docker 文件中运行 `git clone`?