http://www.perlmonks.org?node_id=186892


in reply to regex (?{CODE}) question

The print command isn't executed because it's not in the regex. The first portion of the s/// (between the first two //'s) is a regex; the other portion could be considered a string. So you need to place the (?{ print $1 }) at the end of the regex part, like so:
$str = "(<ref links=\" cit314-1 cit314-2 cit314-3 cit314-4 cit314-5\"/ +>)"; if( $str =~ s/<ref links="(.*?)"(.*?)\/>(?{ print $1, "\n" })/<ref lin +ks="$1"$2><\/ref>/ ){ print "Match was found." . "\n"; } print $str . "\n";
Notice I also didn't escape the quotes -- this isn't necessary and, I think, it makes things look a little messier.

elusion : http://matt.diephouse.com

Replies are listed 'Best First'.
Re: Re: regex (?{CODE}) question
by Ferret (Scribe) on Aug 01, 2002 at 19:34 UTC

    And don't forget, since you're referring to a capture while still in the regex, it hasn't set $1 yet, so you have to use \1 instead:

     (?{ print $1, "\n" })

    would need to be

     (?{ print \1, "\n" })

    unless there's something special about the codeblock I'm not aware of?

    Update: Strike that, reverse it, elusion's correct. Make sure you don't do anything silly like using \1 instead of $1 ;-)

      While in a code block, $1 is correct. This is necessary because it's executed as actual code. I'm not sure how \1 would actually parse, though I assume it'd be a reference to 1.

      elusion : http://matt.diephouse.com

        Thanks for your reply. Actually, my objective is not to print $1 but to call a subroutine from inside the replace part of the regex which will use the value of $1 to produce a string that will be used in the replace part. For example, something like:
        $str = "(<citationref linkend=\" cit314-1 cit314-2 cit314-3 cit314-4 c +it314-5\"/>)"; if( $str =~ s/<ref links=\"(.*?)\"(.*?)\/>/<ref links=\"$1\"$2>(?{ &ge +tString($1) })<\/ref>/ ){ print "Match was found." . "\n"; } print $str . "\n"; sub getString($s){ my $s = shift; ...more processing of $s... return $s; }
        Thanks,
        Christos