Cha*_*hap 2 perl hash each tie
Tie :: IxHash生成一个对象,该对象具有大部分完整的行为集,如数组和散列.但我找不到each函数的等价物,它返回(键,值)对.
我只是忽略了它吗?
如果我必须自己动手,我会认为这样的事情会起作用:
use Tie::IxHash;
$t = Tie::IxHash->new( a,1,b,2,c,3 );
while (($x1, $x2) = map { $_ => $t->Values($_) } $t->Keys ) { say "$x1 => $x2"; }
Run Code Online (Sandbox Code Playgroud)
但输出是一系列无限的
a => 1
Run Code Online (Sandbox Code Playgroud)
......出于我尚不清楚的原因.
任何人都能建议如何each使用绑定哈希?
Tie::IxHash没有Each方法,但你可以each在绑定的哈希上使用Perl的函数:
use Tie::IxHash;
my $t = tie my %hash, 'Tie::IxHash';
@hash{qw/a b c d e/} = (1, 2, 3, 4, 5);
# using the tied hash
while (my ($key, $val) = each %hash) {
print "$key => $val\n";
}
# using the OO interface (interchangeably)
foreach my $key ($t->Keys) {
my $val = $t->FETCH($key);
print "$key => $val\n";
}
Run Code Online (Sandbox Code Playgroud)
请注意,这$t->Values($key)将无效.此方法期望索引不是键.这将有效:
foreach (0 .. $t->Length - 1) {
my ($key, $val) = ($t->Keys($_), $t->Values($_));
...
}
Run Code Online (Sandbox Code Playgroud)