Reputation: 10322
@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 ?
Upvotes: 5
Views: 6352
Reputation: 563
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";
Upvotes: 1
Reputation: 62019
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'
];
Upvotes: 10
Reputation:
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{$_};
}
Upvotes: 4