Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two arrays without any duplicates

Tags:

perl

@tools = ("hammer", "chisel", "screwdriver", "boltcutter",
           "tape", "punch", "pliers"); 
@fretools =("hammer", "chisel", "screwdriver" ,"blade");

push @tools,@fretools if grep @tools,@fretools

and i have get tools

  @tools=("hammer", "chisel", "screwdriver", "boltcutter", 
       "tape", "punch", "pliers", "blade");

is there any easy way to do ?

like image 280
Tree Avatar asked Jul 15 '10 13:07

Tree


1 Answers

The List::MoreUtils CPAN module has a uniq function to do this. If you do not want to rely on this module to be installed, you can simply copy the uniq function from the module's source code (since it is pure Perl) and paste it directly into your own code (with appropriate acknowledgements). In general, the advantage of using code from CPAN is that its behavior is documented and it is well-tested.

use strict;
use warnings;
use Data::Dumper;

sub uniq (@) {
    # From CPAN List::MoreUtils, version 0.22
    my %h;
    map { $h{$_}++ == 0 ? $_ : () } @_;
}

my @tools = ("hammer", "chisel", "screwdriver", "boltcutter",
             "tape", "punch", "pliers"); 
my @fretools =("hammer", "chisel", "screwdriver" ,"blade");
@tools = uniq(@tools, @fretools);
print Dumper(\@tools);

__END__

$VAR1 = [
          'hammer',
          'chisel',
          'screwdriver',
          'boltcutter',
          'tape',
          'punch',
          'pliers',
          'blade'
        ];
like image 130
toolic Avatar answered Nov 02 '22 21:11

toolic