You're not taking into account the non-greediness. To accommodate matching the $ (which is before the newline) $1 holds 'foo'. If you also want to match the terminal newline, use \z instead of $:
$ perl -e '$_="foo\n"; print "1=|$1|\n" if m/(fo.+?)$/s' 1=|foo| $ perl -e '$_="foo\n"; print "1=|$1|\n" if m/(fo.+?)\z/s' 1=|foo |
Your comparison with the first one-liner is not comparing apples with apples:
$ perl -e '$_="foo\nbar"; print "1=|$1|\n" if m/(fo.+?)$/s' 1=|foo bar| $ perl -e '$_="foo\nbar\n"; print "1=|$1|\n" if m/(fo.+?)$/s' 1=|foo bar| $ perl -e '$_="foo\nbar\n"; print "1=|$1|\n" if m/(fo.+?)\z/s' 1=|foo bar |
I also second ++Fletch's recommendation to use Regexp::Debugger. This allows you to step through the matching process and see exactly what's happening. I often use it myself.
— Ken
In reply to Re^3: Non-greedy match end of line bug?
by kcott
in thread Non-greedy match end of line bug?
by am12345
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |