in reply to Re: Using lookaround with variables
in thread Using lookaround with variables

Thanks a lot everyone for all the hints. Just to clarify, the variables would contain plain text, not a pattern. I have now tried the following two expressions, but neither of the works:
if( $line =~ m/(?<!\Q$pre\E)\Q$searchTerm\E(?!\Q$post\E)/ ) {print $line}; if( $line =~ m/(?<!$pre)$searchTerm(?!$post)/ ) {print $line};
Strangely enough, if I put in the contents of the variables $pre and $post directly into the RegEx, then it does work. Any ideas why that might be?

Cheers,

Martin

Replies are listed 'Best First'.
Re^3: Using lookaround with variables
by mwunderlich (Initiate) on Dec 17, 2008 at 14:34 UTC
    OK, so investigating this further, it seems that the error not actually caused by the RegEx, but rather by the code that follows it - which I find even stranger.

    The following works:
    while (<MYFILE>) { $line = $_; if( $line =~ m/(?<!$pre)$searchTerm(?!$post)/ ) {print $line}; }
    The following doesn't work:
    while (<MYFILE>) { $line = $_; if( $line =~ m/(?<!$pre)$searchTerm(?!$post)/ ) {print $line}; if ($pre = "" and $post = "") { print "Case 1"; } elsif ($pre = "") { print "Case 2"; } elsif ($post = "") { print "Case 3"; } else { print "Case 4"; } print "\n"; }
    Any ideas why??

    Cheers,

    Martin

      Always use strictures (use strict; use warnings;). Oh, I already said that!

      Your problem is/was that you are using = instead of == for testing numeric equality. Using strictures you'd have gotten the message:

      Found = in conditional, should be == at ...

      the first time you tried running the code. It would have cost 30 seconds to add strictures and about 15 minutes or maybe a lot less (depending how big your actual code is of course) to clean up your code. Glancing at the times of your postings that would have given you about 1.5 hours you could have been drinking beer or reacquainting yourself with the wife instead of chasing frustrating bugs.


      Perl's payment curve coincides with its learning curve.
      Playing around with this even more, I can now answer my own question (and show how much of a beginner's question this). It all boiled down to two syntax errors:
      - using "and" instead of "&&" as the boolean operator
      - using "$pre = """ instead of "!$pre" to check for empty strings.

      All solved.

      Cheers, Martin