Eval Code Blocks or subroutines in a Perl Regular Expression
Some times you need some intelligence behind your Perl regular expressions, so you need to capture some pieces of text into $1, $2,… and then process them before you replace them in the string.
Simple example you need to convert multiple dates included in a big string from 12/24/2009 to 2009-12-24.
You could do the following:
my $line = "abc","cde","12/24/2009","fff","11/23/2008","sss";
my $rr = \&my_sub;
$line =~ s/(\d{1,2})\/(\d{1,2})\/(\d{4})/$rr->($1,$2,$3)/ge;
print $line;
sub my_sub {
my ($s1, $s2, $s3) = @_;
return sprintf("%04d-%02d-%02d",$s3,$s1,$s2);
}
Notice the /ge in the regular expression? That is what gets your code executed before the substitutions get made. This being Perl I know there are another 200 ways of doing this differently, and I am sure 198 are faster and simpler. Care to comment? What is your way of doing this?
9yYEWj comment2 ,
Eolksrqk
May 8, 2009 at 8:53 am
You can just say
$line =~ s/(\d{1,2})\/(\d{1,2})\/(\d{4})/&my_sub($1,$2,$3)/ge;
Phil Goetz
February 7, 2012 at 6:59 pm
Thank you, you’ve saved me a lot of hair pulling!
Colin Wood
March 9, 2012 at 10:49 pm