0

In Perl:

 my %members = ( "fools"      => 6,                      
                 "monsters"    => 2,                      
                 "weirdos"       => 1,                      
                 "coders"    => 1,                                        
                 "betrayers"     => 1,   );     

When I write:

 my @values_members = values %members;

The position of the elements in the array will not be 6, 2, 1, 1, 1 (the position "as they appear" in the code). It will be random or close to random.

I want a function such that:

 my values_members = get_values_with_position_as_appears_in_code ( %members );

gives

 ( 6, 2, 1, 1, 1 );

Is this possible?

ado
  • 1,451
  • 3
  • 17
  • 27
  • 1
    [This other thread](http://stackoverflow.com/questions/1558625/how-can-i-maintain-the-order-of-keys-i-add-to-a-perl-hash) might be of some help... :) – summea Aug 30 '13 at 05:02

1 Answers1

5

Perl hashes are unordered, so there is no particular guarantee about what order you will get things out of the hash.

You can use Tie::IxHash which will give you a hash that keeps track of its insertion order.

use strict;
use warnings;

use Tie::IxHash;

tie my %members, 'Tie::IxHash', ( "fools"      => 6,                      
                                  "monsters"   => 2,                      
                                  "weirdos"    => 1,                      
                                  "coders"     => 1, 
                                  "betrayers"  => 1,   );

my @values = values %members;

print join "\n" @values;

Output:

6
2
1
1
1
friedo
  • 65,762
  • 16
  • 114
  • 184