tags:

views:

79

answers:

3
@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 ?

+4  A: 

There is sure to be a module which does this for you BUT without a module:

my %uniques;
@uniques{@tools} = @tools x (1);
@uniques{@fretools} = @fretools x (1);
@tools = sort keys %uniques;

This puts the tools in a different order. If you want to keep the order, you need a different method.

my %uniques;
@uniques{@tools} = @tools x (1);
for (@fretools) {
    push @tools, $_ if ! $uniques{$_};
}
Kinopiko
+6  A: 

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'
        ];
toolic
+1 A variant that's even more compact: `map { $h{$_}++ ? () : $_ } @_`.
FM
+1  A: 

You could try using a hash, then extract the keys to get the unique elements:

use strict; 

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

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

my %hash   = map { $_, 1 } @tools;
my @array = keys %hash;

print "@array";
Joe Suarez