Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Here's uniq from List::MoreUtils:

sub uniq (@) { my %h; map { $h{$_}++ == 0 ? $_ : () } @_; }

I think this is equivalent to your "my %h; @uniq = grep { ! $h{$_}++ } @in;". What's important about both of them is that they don't do this:

sub bad_uniq { my %h; @h{@in} = (); return keys %h; }

...which may be more succinctly (idiomatically) written as "keys %{{ map { $_ => 1 } @in }}".

The difference is that keys will not return what was in the list to begin with but rather whatever those things come out as after being stringified. The solutions using map and grep both will stringify the stuff you feed them, but it's the stuff that's returned, and not the stringy leftovers that were used to tell which were duplicates.

Update with a demonstration:

use List::MoreUtils 'uniq'; use Data::Dumper; my $aref = [ 1, 2 ]; my @aref_duplicated = ( $aref, $aref, $aref ); my @u1 = uniq( @aref_duplicated ); my @u2 = keys %{{map {$_=>1} @aref_duplicated}}; print Data::Dumper->Dump( [ \@u1, \@u2 ], [ '*from_uniq', '*from_keys' ] ); __END__ @from_uniq = ( [ 1, 2 ] ); @from_keys = ( 'ARRAY(0x8153c28)' );

In reply to Re^3: Idiom: hashes as sets by kyle
in thread Idiom: hashes as sets by vrk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-19 23:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found