develooper Front page | perl.beginners | Postings from March 2002

Re: using search backreferences in a variable

Thread Previous | Thread Next
From:
Jeff 'japhy' Pinyan
Date:
March 28, 2002 08:07
Subject:
Re: using search backreferences in a variable
Message ID:
Pine.GSO.4.21.0203281055230.6722-100000@crusoe.crusoe.net
On Mar 28, Bryan R Harris said:

>Why does this segment not work properly?

You would know if you had warnings turned on.

  perl -we '$match = "cat(\d+)"'

yields the warning

  Unrecognized escape \d passed through at -e line 1.

>$match = "cat(\d+)";
>$replace = "\1dog";
>$_ = "cat15";
>s/$match/$replace/g;
>print $_;  # prints -->  \1dog

Nope, that prints cat15.  Why?  Because "cat(\d+)" is the same as
"cat(d+)" because "\d" becomes "d".  If you had used single quotes, you
would have been ok.  And $replace the string "_dog", where that _
represents an unprintable character -- specifically, character 1 (SOH).

If you had done:

  $match = 'cat(\d+)';
  $replace = '\1dog';
  $_ = "cat15";
  s/$match/$replace/;
  print;

You would get CLOSER, but not entirely there.  $match would be correct,
but you would get \1dog instead of 15dog.

To fix that requires a bit of work.  Here are two solutions:

  $match = 'cat(\d+)';
  $replace = '$1dog';   # XXX: you should not use \1 on the right-hand
                        # side of a regex; you should use $1
  $_ = "cat15";
  s/$match/qq(qq($replace))/ee;  # qq() is just a fancy "..."
  print;

What does THAT do?  Well, first, each /e modifier means "execute the
right-hand side as code".  Since there are two /e's, we'll be executing it
TWICE.  The first time, qq(qq($replace)) returns the text qq($1dog).  When
we execute that, we get "15dog".

The other way might be easier to understand:

  $match = 'cat(\d+)';
  $replace = sub { "$1dog" };
  $_ = "cat15";
  s/$match/$replace->()/e;
  print;

This uses a function reference stored in $replace.  What this does is
delay the evaluation of $1 until it's needed.

-- 
Jeff "japhy" Pinyan      japhy@pobox.com      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About