in reply to Repeated code blocks in long and hairy regex

When you add the eval, it evaluates the regular expression as a string. This will likely remove one layer of backslashes ("escapes").

I wonder where you got the idea of wrapping eval around a regular expression definition from and why you think it would change the program outcome to one you expect?

Replies are listed 'Best First'.
Re^2: Repeated code blocks in long and hairy regex
by Polyglot (Chaplain) on Nov 05, 2023 at 11:12 UTC
    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~

      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~