[clug-progsig] Perl array disorder

William Astle lost at l-w.ca
Fri Aug 15 13:16:56 PDT 2008


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;

This makes @TestArray, an array.

> $TestArray->{'1'} = "one";
> $TestArray->{'2'} = "two";
> $TestArray->{'3'} = "three";
> $TestArray->{'4'} = "four";

The above adds entries to a hash that is referenced by the scalar
$TestArray.

> foreach $key (keys %{$TestArray})
> {
>         print "key=$key, value = ".$TestArray->{$key}."\n";
> }

The above iterates over the keys in the hash referenced by the scalar
$TestArray.

> root at QtCompiler[~] #./PerlArrayDisorder.pl
> key=4, value = four
> key=1, value = one
> key=3, value = three
> key=2, value = two
> 
> 

Your problem is that you are using *hashes*, not *arrays*. Arrays are
indexed by [] while hashes are indexed by {}.

Your code actually has three things in it: an array that is declared
local but never used, a scalar called $TestArray, and an anonymous hash
(which $TestArray contains a reference to).

The following is approximately what you thought you were doing:

#!/usr/bin/perl
my @TestArray;
push (@TestArray, "one");
push (@TestArray, "two");
push (@TestArray, "three");
push (@TestArray, "four");
foreach $value (@TestArray)
{
	print "$value\n";
}

Note that arrays are indexed from 0.

push() adds an element to the end of the array.

$#TestArray would return the highest index in the array. That would be 3
in the above example. (Indexes that exist would be 0, 1, 2, 3).



More information about the clug-progsig mailing list