【发布时间】:2014-01-30 19:44:25
【问题描述】:
为了帮助我学习 Perl,我构建了以下数据结构,其中内部哈希(/DriveA/archive 等)是哈希引用:
#The contents of the %properties hash of hashes
#The inner hash is a hash reference to a hash named %attributes
$VAR1 = {
'/DriveA' => {
'/DriveA/archive/' => {
'MaxSize' => '20GB',
'Size' => '19GB',
'Free' => '5'
},
'/DriveA/current/' => {
'MaxSize' => '20GB',
'Size' => '12GB',
'Free' => '40'
}
},
'/DriveB' => {
'/DriveB/archive/' => {
'MaxSize' => '8GB',
'Size' => '6GB',
'Free' => '25'
},
'/DriveB/current/' => {
'MaxSize' => '80GB',
'Size' => '20GB',
'Free' => '75'
}
},
'/DriveC' => {
'/DriveC/' => {
'MaxSize' => '20GB',
'Size' => '10GB',
'Free' => '50'
}
}
}
我创建了一个数组来保存 %attributes 的键(又名 %properties 中的值/哈希引用),使用:
@list = sort keys %attributes;
我正在尝试遍历@list 中的元素并在%properties 中找到外部哈希的关联键。因此,例如,如果 /DriveA/archive/ 是数组中的下一项,我想从 %properties 中找到与该值关联的哈希键 /DriveA,假设取消引用内部哈希。
我创建了一个反向哈希,它输出以下内容...
$VAR1 = {
'HASH(0x2002f244)' => '/DriveB',
'HASH(0x2002f388)' => '/DriveC',
'HASH(0x2002f1e4)' => '/DriveA'
}
...使用此代码...
foreach my $item (@list) {
my %rhash = reverse %properties; # Reverse the hash of hashes so value is key
print Dumper(\%rhash);
}
问题一:
鉴于上述情况,我将如何取消引用哈希,以便我可以在哈希引用中找到$item,这样我就可以确定关联的值(而不是哈希引用值)。
如果是$item = '/DriveA/archive/',我想在%properties 的变量中捕获'/DriveA',以便可以从子程序返回。
我知道内部散列需要被取消引用,我只是不知道该怎么做。我已经阅读了perlref、perldsc 和perllol,但一直没有找到答案。
谢谢。
【问题讨论】:
-
据我所知,您正试图从基本上是引用的字符串表示形式中获取数据结构引用。不要那样做。那种方式是疯狂的。
标签: perl hash perl-data-structures hash-of-hashes hashref