Re: Dynamically creating a hash for keys()
[email protected] (Craig S . Cottingham)
| Newsgroups | perl.fwp |
|---|---|
| Message-ID | <[email protected]> |
On Oct 19, 2004, at 08:50, Jason Foster wrote:
> Can anyone help me to understand why this code refuses to compile?
> Even better, can anyone help fix it :)
>
> %hash = qw( fred filntstone barney rubble tom delong );
> print( keys( reverse( %hash ) ) );
>
> The error message...
>
> Type of arg 1 to keys must be hash (not reverse) at ./killme.pl
> line 4, near ") ) "
>
> ... was pretty confusing since it implies that "reverse" is a type?!
$ perldoc -f keys
keys HASH
...
$ perldoc -f reverse
reverse LIST
In list context, returns a list value consisting of the
ele-
ments of LIST in the opposite order. In scalar context,
con-
catenates the elements of LIST and returns a string
value with
all characters in the opposite order.
reverse returns a list. keys expects a hash.
Reversing a hash doesn't make sense, assuming you're thinking of
reverse in the same sense as a list. The members of a hash are not
stored in the order in which they were inserted; if you iterate a hash,
the order in which you visit members is dependent only on the
implementation of the hash. In other words, if order is important to
you, don't use a hash.
On the other hand, you can *invert* the hash, swapping keys with
values. I think that's in the perlfaq.
-1 for fun.
--
Craig S. Cottingham
[email protected]
OpenPGP key available from:
http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x7977F79C