Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
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 ( [id://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.

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://99774]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (7)
As of 2024-04-19 13:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found