Given a hash in Perl (any hash), how can I extract the values from that hash, in the order which they were added and put them in an array?
Example:
my %given = ( foo => '10', bar => '20', baz => '15' );
I want to get the following result:
my @givenValues = (10, 20, 15);
From perldoc perlfaq4
: How can I make my hash remember the order I put elements into it?
Use the
Tie::IxHash
from CPAN.use Tie::IxHash; tie my %myhash, 'Tie::IxHash'; for (my $i=0; $i<20; $i++) { $myhash{$i} = 2*$i; } my @keys = keys %myhash; # @keys = (0,1,2,3,...)
The following will do what you want:
my @orderedKeys = qw(foo bar baz);
my %records = (foo => '10', bar => '20', baz => '15');
my @givenValues = map {$records{$_}} @orderedKeys;
NB: An even better solution is to use Tie::IxHash or Tie::Hash::Indexed to preserver insertion order.
If you have a list of keys in the right order, you can use a hash slice:
my @keys = qw(foo bar baz);
my %given = {foo => '10', bar => '20', baz => '15'}
my @values = @given{@keys};
Otherwise, use Tie::IxHash
.
You can use values
, but I think you can't get them in the right order , as the order has been already lost when you created the hash
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With