http://qs321.pair.com?node_id=188986

chuleto1 has asked for the wisdom of the Perl Monks concerning the following question:

Help Monks!
I would like to know how to have my @array keep one instace of repeated elements. (e.g.)

my @array = qw( foo bar match zoot zoot match match match ) ;

#do something here to the array

print @array;
Out put: foo bar match zoot

thank you
  • Comment on Having repeated intances become one in Array

Replies are listed 'Best First'.
Re: Having repeated intances become one in Array
by mephit (Scribe) on Aug 09, 2002 at 18:08 UTC
    my @array = qw( foo bar match zoot zoot match match match ); @array = grep { ! $hash{$_}++} @array;
    Check 'perldoc -q duplicate'

    --

    There are 10 kinds of people -- those that understand binary, and those that don't.

Re: Having repeated intances become one in Array
by vek (Prior) on Aug 09, 2002 at 18:05 UTC
    There are a couple of different ways to handle your dilemma , here's one method using a hash to keep track of what you've already seen:
    my %seen; for my $foo (@array) { print $foo unless $seen{$foo}++; }
    -- vek --
Re: Having repeated intances become one in Array
by ehdonhon (Curate) on Aug 09, 2002 at 18:37 UTC
Re: Having repeated intances become one in Array
by tadman (Prior) on Aug 09, 2002 at 18:56 UTC
    #!/usr/bin/perl my @array = qw[ foo bar baz bar foo baz baz bad ]; sub dedupe { ${_}=do{{},[],{}};@{${_}}{@_,%_,@_}=$|;keys%{\%{${_}}} } print dedupe(@array);
      i'm just a novice in perl...could you please explain how your code works ? i'm sure i could learn a lot from your code thanks :-)