perl - Is hashref in array?

Hill, Greg grhill at corp.untd.com
Tue Jan 9 17:56:00 MST 2007


Can't you just do:

my %seen = ();
my @unique = grep { !$seen{$_}++ } @tree;

Or am I missing something?

Greg

> -----Original Message-----
> From: plug-bounces at plug.org [mailto:plug-bounces at plug.org] On Behalf
Of
> Alan Young
> Sent: Tuesday, January 09, 2007 10:35 AM
> To: Provo Linux Users Group Mailing List
> Subject: Re: perl - Is hashref in array?
> 
> 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.
> 
> /*
> PLUG: http://plug.org, #utah on irc.freenode.net
> Unsubscribe: http://plug.org/mailman/options/plug
> Don't fear the penguin.
> */



More information about the PLUG mailing list