Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: How I learned to stop worrying and love the hash slice. (boo)

by PrakashK (Pilgrim)
on Jul 25, 2001 at 22:59 UTC ( #99774=note: print w/ replies, xml ) Need Help??


in reply to How I learned to stop worrying and love the hash slice. (boo)
in thread beyond me

I frequently use hash slices to eliminate duplicates from an array.

A simplified example:

my @a = (1,2,3,2,1); my %a; @a{@a} = (1) x @a; my @unique_a = keys %a;
Of course, this does not preserve the order of the elements as they were in original array @a.


Comment on Re: How I learned to stop worrying and love the hash slice. (boo)
Download Code
Re: Re: How I learned to stop worrying and love the hash slice. (boo)
by blakem (Monsignor) on Aug 14, 2001 at 14:24 UTC
    Perhaps grep might work better here?
    my @a = (1,2,3,2,1); my %seen; my @unique_a = grep {!$seen{$_}++} @a; print "A: $_\n" for (@a); print "Unique: $_\n" for (@unique_a);
    Assuming you wanted to keep the first occurance, this will preserve the original order.

    Or you can use map to create your %a hash.

    my @a = (1,2,3,2,1); my %a = map {$_=>1} @a; my @unique_a = keys %a; print "A: $_\n" for (@a); print "Unique: $_\n" for (@unique_a);

    -Blake

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://99774]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (7)
As of 2015-07-05 14:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (67 votes), past polls