Re: Dynamically creating a hash for keys()

[email protected] (Bernard El-Hagin)
Newsgroups perl.fwp
Message-ID <[email protected]>

Well, this is hardly fun, but...


Jason Foster <[email protected]> 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 ") ) "


keys() only accepts a hash as an argument. reverse() returns a list. So
you are trying to execute keys() on a list, which results in the error.


>... was pretty confusing since it implies that "reverse" is a type?!
>
>I tried making an anonymous hash as follows...
>
>     print( keys( %{ reverse( %hash ) } ) );


You are trying to dereference something which is not a reference. You
are not creating an anonymous hash at all. The operator which creates an
anonymous hash is {}, not %{}. So first, create the reversed hash


  { reverse %hash }


*then* dereference it


  %{ { reverse %hash } }


But that is so ugly it doesn't bear looking at.


Better to go with


my %r_hash = reverse %hash;


if you sure you are really trying to reverse the key/value pairs.


-- 
Cheers,
Bernard
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.