I was looking for a way to maintain the order of hash keys,
and the only solutions I could find where to either populate a "sort" keys of the position and sort by that, or use Tie::IxHash.
As most, I hate adding another module dependency unless necessary....
So, this is what I came up with:
Hope you like it!
and the only solutions I could find where to either populate a "sort" keys of the position and sort by that, or use Tie::IxHash.
As most, I hate adding another module dependency unless necessary....
So, this is what I came up with:
Code:
sub iterator {
my @index;
my %hash;
for my $i ( 0 .. ( scalar @_ ) - 1 ) {
next if ($i % 2);
$hash{$_[$i]} = $_[($i + 1)];
push @index, $_[$i];
}
return sub {
return () if !@index;
my $key = shift(@index);
if ( wantarray ) {
return ($key, $hash{$key});
}
else {
return $key;
}
}
}
my $i = iterator(
one => 1,
two => 2,
three => 3
);
while ( my ($key, $value) = $i->() ) {
print "$key => $value\n";
}
## O R ##
while ( my $k = $i->() ) {
print "$k\n";
}
Hope you like it!