develooper Front page | perl.beginners | Postings from April 2002

RE: associative array not looking like I thought it would

Thread Previous
From:
David Gray
Date:
April 26, 2002 09:09
Subject:
RE: associative array not looking like I thought it would
Message ID:
000601c1ed3c$99c575c0$7800a8c0@3b2.com
> This was all written by a vendor and I am trying to learn 
> PERL to modify what they did.  When you say I must print it 
> explicitly, what exactly do you mean?

You have to _sort_ it explicitly. In Timothy's example, he was sorting
the hash alphabetically based on the keys. The keys function returns a
temporary array which contains the ...*dramatic pause*... keys of the
hash, which are then sorted alphabetically and used to access the hash.

Perl internally optimizes and re-orders hashes, so if you want them to
be in the same order they were inserted in, consider using an array of
arrays, like so:

@Error=( [Error=>"[$ciTDF{'#errval_V'}]: $ciTDF{'#errtext_V'}"],
         ['Document Name'=>$ciTDF{'DOC_NAME_V'}],
         [Revision=>$ciTDF{'DOC_REV_V'}],
         [Desc=>"Issuing-could not index to vault"],
         [Notes=>"Clean Vault Log"] );

If you plan to do it this way, or if you're just curious, you should
read the perlreftut manpage by typing 'perldoc perlreftut' at the
command line. You can then access your variables like this:

$Error[2]->[0]; # access the first value
                # of the third element inserted


And print them sorted alphabetically by the first value like so:

foreach(sort {$a->[0] cmp $b->[0]} @Error) {
  print "'$_->[0]' => '$_->[1]'\n";
}

HTH,

 -dave



Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About