Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract hash values into an array in their insertion order?

Tags:

hash

perl

tie

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);
like image 238
Tom Avatar asked Aug 03 '10 13:08

Tom


4 Answers

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,...)
like image 164
Zaid Avatar answered Nov 01 '22 15:11

Zaid


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.

like image 22
dsm Avatar answered Nov 01 '22 15:11

dsm


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.

like image 24
Eugene Yarmash Avatar answered Nov 01 '22 15:11

Eugene Yarmash


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

like image 2
mb14 Avatar answered Nov 01 '22 17:11

mb14