如何通过散列的Perl散列中的值访问键?
问题描述:
我已经散列的散列这样的:如何通过散列的Perl散列中的值访问键?
$hashtest{ 1 } = {
0 => "A",
1 => "B",
2 => "C"
};
例如,我怎样才能取散列{1}的B的值?
$hashtest{'B'}{1}
答
$hashtest{ 1 } = { 0 => "A", 1 => "B", 2 => "C" };
my $index;
my $find = "B";
foreach my $key (keys %{ $hashtest{1} }) {
if($hashtest{1}{$key} eq $find) {
$index = $key;
last;
}
}
print "$find $index\n";
答
$hashtest{1}{1};
答
其他人提供众所周知的鱼
Perl有免费在线(在命令提示符)文档。下面是一些相关链接:
答
根据你对其他答复 可以扭转的哈希评论,(即交换密钥和值。) 。
但要小心,只有在您确定 之后才能做到这一点,原始 中没有重复值,因为此操作仅保留其中的一个。
#!/usr/bin/perl
use 5.10.1;
use warnings;
use strict;
my %hashtest;
$hashtest{ 1 } = { 0 => "A", 1 => "B", 2 => "C" };
my %rev = reverse %{$hashtest{1}};
say $rev{B};
输出:
答
既然你已经使用号码的散列键,在我看来,你应该使用数组来代替。否则,在反转散列时,您将丢失重复的键。
示例代码:
use strict;
use warnings;
use List::MoreUtils 'first_index';
my $find = 'A';
my @array = qw{ A B C };
my $index = first_index { $_ eq $find } @array;
Perl Data Structures Cookbook将帮助您了解在Perl的数据结构。
答
如果所有的按键都是整数,你最想处理数组,而不是哈希:
$array[1] = [ qw(A B C) ]; # Another way of saying [ 'A', 'B', 'C' ]
print $array[1][1]; # prints 'B'
但是,如果我知道的价值,我想索引?例如,我想知道哈希{1}的'A'的“索引”? – user476918 2010-10-15 13:45:00