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

Re: using search backreferences in a variable

Thread Previous | Thread Next
Jeff 'japhy' Pinyan
March 28, 2002 08:07
Re: using search backreferences in a variable
Message ID:
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";
>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";

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 "..."

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";

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

Jeff "japhy" Pinyan
RPI Acacia brother #734
** 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 Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About