in reply to match last element instead of first??

m/(.*)fish/ makes perl go all the way to the end of the string and then back up to find fish...

m/^(.*?)fish/ tells perl to match as little as possible while still finding fish afterwards. It will only match zero characters though, unless you tell it to start from the beginning.

It's all explained rather well in perlre. I read that every year or so still and I've been at this quite a while. I also recommend reading perldata and perlref on a semi-regular basis.

-Paul

Replies are listed 'Best First'.
Re^2: match last element instead of first??
by moritz (Cardinal) on Oct 17, 2007 at 17:11 UTC
    ... and m/fish(.*?)$/ makes perl go to the end of the string, match as little as possible (from back to front), and then fish.

    Update: After rereading the original message that was not asked ;-). But it may still be worth noting that anchoring is a good idea if there is no compelling reason against it.

    Second update: ignore this node ;)

      No:

      perl -le "$_=shift; m/fish(.*?)$/ and print $1" "one fish two fish thr +ee fish"

      gives

      two fish three fish

      .*? will match as little as necessary, but it will not match as little as possible. The fish will still match at the leftmost position. Then, the .*? will match as little as necessary to make the match succeed, which still is the rest of the string.