Reputation: 1
Basically I wanted to emulate the piped grep operation as we do in shell script, (grep pattern1 |grep pattern2) in my Perl code to make the result unique.
Below code is working, bust just wanted to know this is the right approach. Please note, I don't want to introduce a inner loop here, just for the grep part.
foreach my $LINE ( @ARRAY1 ) {
@LINES = split /\s+/, $LINE;
@RESULT= grep ( /$LINES[0]/, ( grep /$LINES[1]/, @ARRAY2 ) );
...
Upvotes: 0
Views: 404
Reputation: 152
There are different ways to grep/extract unique values from array in perl.
##2) Best of all
my %hash = map { $_ , 1 } @array;
my @uniq = keys %hash;
print "\n Uniq Array:", Dumper(\@uniq);
##3) Costly process as it involves 'greping'
my %saw;
my @out = grep(!$saw{$_}++, @array);
print "\n Uniq Array: @out \n";
Upvotes: 0
Reputation: 126722
There is no need to cascade calls to grep
-- you can simply and the conditions together
It's also worth saying that you should be using lower-case letters for your identifiers, and split /\s+/
should almost always be split ' '
Here's what I would write
for my $line ( @array1 ) {
my @fields = split ' ', $line;
my @result = grep { /$fields[0]/ and /$fields[1] } @array2;
...
}
Upvotes: 1
Reputation: 50637
This is basically same thing what you're doing, "for every @ARRAY2
element, check whether it matches ALL elements from @LINES
" (stop as soon as any of the @LINES
element does not match),
use List::Util "none";
my @RESULT= grep { my $s = $_; none { $s !~ /$_/ } @LINES } @ARRAY2;
# index() is faster for literal values
my @RESULT= grep { my $s = $_; none { index($s, $_) <0 } @LINES } @ARRAY2;
Upvotes: 1