perl - Is hashref in array?

Alan Young alansyoungiii at gmail.com
Tue Jan 9 10:35:07 MST 2007


Andrew Jorgensen wrote:
> #!/usr/bin/perl
> use strict;
> use warnings;
> use Data::Dumper;
> 
> my @tree;
> my $zero = { a => "0", b => "0" };
> my $one = { a => "1", b => "1" };
> 
> push @tree, $zero, $one, $zero, $one;
> 
> my %saw;
> @saw{@tree} = ();

Perl stringify's references used as key's, which is not what you want. 
If you *really* want to use a reference as a key the best way to do it 
would be to serialize the keys.  Something like:

$saw{ Dumper $_ } = () for @tree;

Then to get it back you would need to do something like

push @tree, eval { $_ } for keys %saw;

Except that wouldn't really work as is, because you lost the name of the 
variable when you pushed it into @tree and then the order when you 
converted it into the hash.  If you embed the name of the hash in the 
hash you might be able to restore the variables that way.  I wouldn't 
recommend it unless you had  no other choice.

If you absolutely must do it then I would use an array to keep track of 
the variable names order in @tree then use that to create the key and 
reconstruct the code later.



More information about the PLUG mailing list