grep unexpected output
am 17.08.2007 22:17:31 von Shion
The following code...
@a1 = ('Test', 'steve');
@a2 = ('All_UPF', 'Cat', 'Happy', 'LegsOnly', 'Master', 'NILS', 'Test',
'steve');
for (@a2) {
if (grep($_, @a1)) {
print "YES: $_\n";
} else {
print "NO: $_\n";
}
}
gives this output...
YES: All_UPF
YES: Cat
YES: Happy
YES: LegsOnly
YES: Master
YES: NILS
YES: Test
YES: steve
I was expecting this output...
NO: All_UPF
NO: Cat
NO: Happy
NO: LegsOnly
NO: Master
NO: NILS
YES: Test
YES: steve
What am i doing wrong? Thank you.
Re: grep unexpected output
am 17.08.2007 22:28:50 von Mirco Wahab
monkeys paw wrote:
> @a1 = ('Test', 'steve');
> @a2 = ('All_UPF', 'Cat', 'Happy', 'LegsOnly', 'Master', 'NILS', 'Test',
> 'steve');
>
> for (@a2) {
> if (grep($_, @a1)) {
> print "YES: $_\n";
> } else {
> print "NO: $_\n";
> }
> }
> What am i doing wrong? Thank you.
$_, which is set in the for loop, is also
produced within grep, so you habe to use
an explicit varable, like:
for my $elem (@a2) {
if( grep(/\Q$elem\E/, @a1) ) {
print "YES: $elem\n";
}
else {
print "NO: $elem\n";
}
}
Furthermore, you have tell grep to do
a textual /$match/ on the loop variable -
which (not in your case) may contain
characters that may have special meaning
within your regular expression /$match/
context. You keep them by "quoting" them
into a digestible form by \Q...\E meta-
characters.
Regards
M.
Re: grep unexpected output
am 18.08.2007 05:01:12 von Paul Lalli
On Aug 17, 4:17 pm, monkeys paw wrote:
> The following code...
>
> @a1 = ('Test', 'steve');
> @a2 = ('All_UPF', 'Cat', 'Happy', 'LegsOnly', 'Master', 'NILS', 'Test',
> 'steve');
>
> for (@a2) {
> if (grep($_, @a1)) {
> print "YES: $_\n";
> } else {
> print "NO: $_\n";
> }
>
> }
>
> gives this output...
>
> YES: All_UPF
> YES: Cat
> YES: Happy
> YES: LegsOnly
> YES: Master
> YES: NILS
> YES: Test
> YES: steve
>
> I was expecting this output...
>
> NO: All_UPF
> NO: Cat
> NO: Happy
> NO: LegsOnly
> NO: Master
> NO: NILS
> YES: Test
> YES: steve
>
> What am i doing wrong? Thank you.
The syntax of grep is:
grep EXPR, LIST
For each element of LIST, it assigns $_ to that element, and then
evaluates EXPR. If EXPR is true for any of those evaluations, the
grep returns true. So what you were doing is looping through @a1 and
testing whether the elements of @a1 are true. Obviously they all
are. And so the grep returned true, and you executed the if block.
Then in that if block, that $_ referred to the elements of @a2 that
you were looping through via the for loop.
So you were doing two things wrong:
1) Using $_ for two different purposes, and not realizing it.
2) only testing the truth of $_, rather than whether or not $_ was
actually equal to some value.
You will need to give an explicit variable name to the foreach loop
iterator, so that you can compare it to the $_ that's created by grep:
for my $a2_elem (@a2) {
if (grep { $a2_elem eq $_ } @a1)) {
print "YES: $a2_elem\n";
} else {
print "NO: $a2_elem\n";
}
}
Paul Lalli