Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: removing duplicate entries from an array

by GrandFather (Sage)
on Nov 07, 2005 at 20:51 UTC ( #506524=note: print w/replies, xml ) Need Help??


in reply to removing duplicate entries from an array

Here is one way:

use strict; use warnings; my @names = qw(Mary Mary Mary Mary Joe Joe Joe); my %unique; @unique{@names} = undef; @names = keys %unique; print join ", ", @names;

Prints:

Joe, Mary

Update s/undef/()/ per Roy Johnson's reply


Perl is Huffman encoded by design.

Replies are listed 'Best First'.
Re^2: removing duplicate entries from an array
by Roy Johnson (Monsignor) on Nov 07, 2005 at 21:37 UTC
    Just a style point: assigning a scalar to a hash slice is quirky. Save a few keystrokes and have dimensional consistency by doing @unique{@names} = () instead.

    Caution: Contents may have been coded under pressure.
Re^2: removing duplicate entries from an array
by davidrw (Prior) on Nov 07, 2005 at 21:21 UTC
    OP asked for quick & dirty :)
    print join ", ", keys %{{map {$_=>undef} @XYZ}};
      Dirtier:
      print join ', ', keys %{(grep \@{$_}{@XYZ}, {})[0]};
      ;-)

      Caution: Contents may have been coded under pressure.

      Dirtier maybe, quicker not:

      use strict; use warnings; use Benchmark qw(cmpthese); my @XYZ = qw(Mary Mary Mary Mary Joe Joe Joe); cmpthese ( -1, { 'GF' => sub {my %unique; @unique{@XYZ} = (); keys %unique;}, 'DW' => sub {keys %{{map {$_=>undef} @XYZ}};}, 'RJ' => sub {keys %{(grep \@{$_}{@XYZ}, {})[0]};}, } );

      Benchmark results:

      Rate DW RJ GF DW 71543/s -- -62% -73% RJ 188025/s 163% -- -28% GF 260808/s 265% 39% --

      Updated to include Roy Johnson's "dirtier" version


      Perl is Huffman encoded by design.
        good point... though depends on OP's definition of "quick & dirty" and if it's in reference to the coding or the actual execution... :)

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2020-12-02 17:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How often do you use taint mode?





    Results (44 votes). Check out past polls.

    Notices?