#!/usr/bin/perl
# perl-grep2.pl
my $pattern = shift @ARGV;
my $regex = eval { qr/$pattern/ };
die "Check your pattern! $@" if $@;
while( <> )
{
print if m/$regex/;
}
I didn't know why my code had had issues to begin with, so when I saw that code example, I thought perhaps I had not used the correct syntax for this usage, and tried it the way they had it. I didn't have anything to lose in trying, but the result was not an improvement.
| [reply] [d/l] |
Note how that code uses the block form of eval, eval { ... }, not the string form eval qr//.
That eval is only there to "protect" you against errors in your regular expression. I'm not sure what the use is in that program as it immediately exits anyway.
You are at least getting tripped up by not understanding the two forms of eval and how they differ. String-eval should rarely be used and regular expressions are not one of these rare cases.
| [reply] [d/l] [select] |
Well, I tried eval because something was already broken. I've removed it now, and have no need for it. I just want my variable to work inside the regular expression. How do I properly quote it, and/or invoke the substitution, so that it will work? I thought this would be easy, but it just did not work as expected. I think the qr// is adding something, because the expression it resolves to is not identical to what I have assigned my variable. But if I use qw// or just q//, those don't seem any better. I just want to drop in a piece of code which looks exactly as I have assigned it to the variable, and, as it happens, I do not need to eval any variables inside my short block of code as there won't be any. So, while simple is the order of the day, it has turned out to be not so simple.
| [reply] |