[clug-progsig] Perl array disorder

John Jardine john_e_jardine at spamcop.net
Fri Aug 15 13:00:00 PDT 2008


Yup, you're using associative arrays which are defined to have an
arbitrary native sequence.  Even if that sequence appears to be what you
want it may change between invocations.

If you want to impose a sequence on the contents of an associative
array, use a structure like:
foreach $arr_key ( sort keys %myAssociativeArray )

If the sort order is something other than a native collating sequence,
you can impose your own by:
foreach $arr_key ( sort { left-side <=> right-side } keys %
myAssociativeArray )
   


On Fri, 2008-08-15 at 13:38 -0600, Royce Souther wrote:
> I don't think I would call this a bug but more just another joke Larry Wall
> is try to play on Perl programmers.
> 
> I am working with a custom config file that looks kind of like badly
> formated XML in that each field may contain any number of entries and
> sub-entries. I stack the data into an array and when I go to pull the data
> back out is is in a different order then when I put it in. This is not a
> problem because the oder of the data is not important as long as the
> hierarchy remains intact. I would like to know if there is a reason for
> this. At some point in the future I may want an array in order and I should
> know what needs to be done to make that way.
> 
> root at QtCompiler[~] #cat ./PerlArrayDisorder.pl
> #!/usr/bin/perl
> #
> 
> my @TestArray;
> $TestArray->{'1'} = "one";
> $TestArray->{'2'} = "two";
> $TestArray->{'3'} = "three";
> $TestArray->{'4'} = "four";
> foreach $key (keys %{$TestArray})
> {
>         print "key=$key, value = ".$TestArray->{$key}."\n";
> }
> root at QtCompiler[~] #./PerlArrayDisorder.pl
> key=4, value = four
> key=1, value = one
> key=3, value = three
> key=2, value = two
> 
> 




More information about the clug-progsig mailing list