[wellylug] Perl regular expression problem with literal $

Grant McLean grant at mclean.net.nz
Mon Jun 2 21:51:43 NZST 2008


On Mon, 2008-06-02 at 20:02 +1200, Peter Davenport wrote:
 
>         Thank you for this response. The escape of the $ character was
>         part of the answer that I needed, but that did not fix it
>         completely. The example cade worked so I knew what to
>         persevere with that. I had a prior match statement with a 'g'
>         option for global and that seemed to swallow up the whole
>         record and thus not match the bit I wanted to extract on the
>         later statement. Removing the 'g' from the prior statement
>         fixed it. I had not expected such interaction between
>         statements.

That would have been rather tricky to track down!

Normally, a Perl regular expression tries to start matching from the
beginning of the string.  The /g modifier is used when you want one
pattern to start matching from the end of the previous match.

One common usage of /g is in a while loop - each pass through the loop
matches the next 'token'.

In your case, it sounds like you had two completely separate regular
expressions matching against the same string.  The /g on the first regex
caused the second regex to start matching from the point in the string
where the first match ended.

One last piece of information to help make sense of what you saw ...
when you use /g, the next *unsuccessful* match will reset the start of
match pointer, so the following regular expression will go back to
matching from the start of the string.

Cheers
Grant



More information about the wellylug mailing list