in reply to Re: Repeated code blocks in long and hairy regex
in thread Repeated code blocks in long and hairy regex

I wonder where you got the idea of wrapping eval around a regular expression definition from...

I got the idea from an online O'Reilly book about "Mastering Perl" here: https://www.oreilly.com/library/view/mastering-perl/9780596527242/ch02.html

Here is the code example that I had seen on that page:

#!/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.

Blessings,

~Polyglot~

Replies are listed 'Best First'.
Re^3: Repeated code blocks in long and hairy regex
by Corion (Patriarch) on Nov 05, 2023 at 11:23 UTC

    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.

      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.

      Blessings,

      ~Polyglot~

        I found Regexp::Debugger quite illustrative when trying to find why a regular expression does not match.

        As you don't show any data for your regular expression and I don't know how Thai is written, I can't conveniently replicate your problem or find why your regexp behaves with your data in a way that you don't want.

        Maybe you can post relevant data (it is likely to be 6 characters, maybe post them using charnames instead of literals), or find the solution yourself stepping through the matching by using Regexp::Debugger.