Skip to content

Eval Code Blocks or subroutines in a Perl Regular Expression

April 4, 2009

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?

Advertisements

From → Perl

3 Comments
  1. 9yYEWj comment2 ,

  2. You can just say

    $line =~ s/(\d{1,2})\/(\d{1,2})\/(\d{4})/&my_sub($1,$2,$3)/ge;

  3. Thank you, you’ve saved me a lot of hair pulling!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: