Question

Tie::IxHash produces an object that has a mostly-complete set of behaviors as both an array and a hash. But I'm not finding the equivalent of the each function, which returns (key,value) pairs.

Have I just overlooked it?

If I have to roll my own, I'd have thought something like this would work:

use Tie::IxHash;
$t = Tie::IxHash->new( a,1,b,2,c,3 );
while (($x1, $x2) =  map { $_ => $t->Values($_) } $t->Keys ) { say "$x1 => $x2"; } 

But the output was an infinite series of

a => 1

... for reasons that aren't clear to me yet.

Anybody able to suggest how to achieve each with a tied hash?

Was it helpful?

Solution

Tie::IxHash doesn't have an Each method, but you can use Perl's each function on the tied hash:

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";
}

Note that $t->Values($key) won't work. This method expects an index not a key. This will work:

foreach (0 .. $t->Length - 1) {
    my ($key, $val) = ($t->Keys($_), $t->Values($_));
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top