Search code examples
perlhashtie

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


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);

Solution

  • 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,...)