in reply to Re: variable interpolation in regexps
in thread variable interpolation in regexps

Well, the simple fact is nothing can be put into $_ to get the regexp some$thing to match against it because $ is more of a placeholder metacharacter to indicate to the regex engine to make matches around EOL, it doesn't actually denote or match any character per se.

Under the popular text formats an EOL is denoted by a Carriage Return or Line Feed or both. So, is it possible to try and match an EOL sequence in a string that doesn't contain either of CR or LF or CR/LF (\r, \n, \r\n respectively)? Well, No, it's simply impossible.

You have to change your regexp to try and match an actual EOL sequence after $ like this.
my $regexp = qr/some$.thing/sm; # or even qr'some$\nthing'm local $_ = "some\nthing"; print " matched $& " if /$regexp/;
You'll notice the use of qr//sm modifiers to get the regexp to work with multiline strings and get . to match newlines. The //sm modifiers are very important as normally, newlines aren't matched by . in regular expressions unless /s is used but we also are working with multiline strings, hence //sm, more info in perlretut.

Not all strings entered from STDIN are newline terminated, e.g. if you were in multi-line mode (via $/ = undef ) and CTRL+D (twice if preceding character wasn't a newline) was used to terminate input, no newline or any character for that matter is appended to the end of the input string.


perl -e '$,=$",$_=(split/\W/,$^X)[y[eval]]]+--$_],print+just,another,split,hack'er

Replies are listed 'Best First'.
Re^3: variable interpolation in regexps
by Locutus (Beadle) on Nov 26, 2006 at 14:35 UTC
    Aaaah, what a light bulb moment - thank you, Firefly258! I was a real blockhead not to see that as an anchor $ can only match a position between two characters or "between" a character and the beginning/end of a string, just as it is with the anchors \b and \B.

    I must confess I'm still not very familiar with the qr// operator (but be assured that perlretut has been pushed onto my 2do stack ;-) so I tried

    my $regexp = 'some$' . "\nthing";

    and, finally, /$regexp/m matched "some\nthing".

    Thanks again. You Monks are great!