(Sent this from wrong addresss; re-posting)

Andrew Gaul wrote:

> Strangely, Perl does not support named groups[1].  This seems to work:
>
>     $ echo foobar | perl -pe 's/foo(bar)/fu${1}01/'
>     fubar01

That is correct. In Perl, using matched groups in the substitution should always be done with the $ operator, not "\". "\" was included "to avoid shocking the sed addicts." Basically, you should think of the right-hand-side of s/// as a normal double-quote perl string, with all normal interpolation, including $1, $2, and $anything_else.

Look at man perlre. Jason's exact problem and Andrew's exact solution are in there:

Warning on \1 vs $1

Some people get too used to writing things like:

           $pattern =~ s/(\W)/\\\1/g;

This is grandfathered for the RHS of a substitute to avoid shocking the sed addicts, but it's a dirty habit to get into. That's because in PerlThink, the righthand side of an "s///" is a double-quoted string. "\1" in the usual double-quoted string means a control-A. The customary Unix meaning of "\1" is kludged in for "s///". How-ever, if you get into the habit of doing that, you get yourself into trouble if you then add an "/e" modifier.

           s/(\d+)/ \1 + 1 /eg;        # causes warning under -w

       Or if you try to do

           s/(\d+)/\1000/;

You can't disambiguate that by saying "\{1}000", whereas you can fix it with "${1}000". The operation of interpolation should not be confused with the operation of matching a backreference. Certainly they mean two different things on the left side of the "s///".

--
Jason Smith
Open Enterprise Systems
Bangkok, Thailand
http://oes.co.th

Attachment: signature.asc
Description: OpenPGP digital signature

_______________________________________________
Siglinux mailing list
[EMAIL PROTECTED]
http://machito.utacm.org/mailman/listinfo/siglinux

Reply via email to