Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!usc!sdd.hp.com!spool.mu.edu!uunet!bu.edu!nntp-read!composer From: composer@chem.bu.edu (Jeff Kellem) Newsgroups: comp.lang.perl Subject: Re: Need clarification of assoc. arrays Message-ID: Date: 30 Jan 91 19:14:24 GMT References: <7457@aspect.UUCP> Sender: news@bu.edu.bu.edu Reply-To: composer@chem.bu.edu Distribution: usa Organization: Boston University Chemistry Department Lines: 64 In-reply-to: dave@aspect.UUCP's message of 28 Jan 91 22:09:25 GMT In article <7457@aspect.UUCP> dave@aspect.UUCP (Dave Corcoran) writes: > > Date: 28 Jan 91 22:09:25 GMT > > printf("Hello world\n"); print 'Hello world\n'; # if (a tiny bit) quicker ;-) > Why is does this script: > > perl -e ' > $keyword{"one"}="ONE"; > $keyword{"two"}="TWO"; > > for $i (%keyword) { > print $i; > }' > yield > twoTWOoneONE > and not > onetwo An associative array is stored as a LIST of ( key, value, key, value, ... ) So, when you just access it as %keyword, you're getting a LIST of the above. If you just want the keys (indices) of the assoc. array, do... for $i (keys %keyword) { ... } or for $i (sort keys %keyword) { ... } if you want to access the assoc. array sorted by the keys. To access just the values assoc. array, use `values': for $value (values %keyword) { ... } or to access both key/value pairs from the assoc. array: while (($key, $value) = each %keyword) { ... } Take a look at the man page entries for `keys', `values', and `each'. > I am trying to print the indices and the contents of the array thus: > > for $i (%keyword) { > printf "the index is %s; the contents are %s\n",$i,$keyword{$i}; > } So, this should be written as for $i (keys %keyword) { print "the index is $i; the contents are $keyword{$i}\n"; } Use `print' instead of `printf' when you can; it is a tiny bit faster. Hope that helps..Enjoy Perl! -jeff Jeff Kellem Internet: composer@chem.bu.edu