tags:

views:

61

answers:

1

Do we have a preg_callback equivalent in Perl ?

Lets say I want to match something and replace it with the return value of the function that is called with the matched thing.

+9  A: 

Use s///e - evaluation modifier and you can put arbitrary perl codes in second part.

$x = "this is a test";
$x =~ s/(test)/reverse($1)/eg;
print $x;

//this is a tset

ref: http://perldoc.perl.org/perlretut.html#Search-and-replace

S.Mark
Thanks for the quick reply, can you give a short example. Say I want to replace the matched thing with its reverse.
Joseph
`my $string = "abc"; (my $reverseString = $string) =~ s/(bc)/reverse $1/e;` will cause `$reverseString` to become `"acb"` . @Joseph : I suggest you edit your question to ask for the reverse example, so I can post this as a separate answer.
Zaid
I have added @Joseph, also thanks for Zaid
S.Mark
you can also use curly braces as the substitution delimiter which makes the second block a bit more "code like" `s{pattern to match} {reverse($1)}e`
Eric Strom