Harry Harry - 3 months ago 7
Perl Question

Perl: Conditional code execution inside regex pattern

I'm aware of the so-called experimental

(?{ ... })
facility in Perl 5 to execute code as such
print
statements, setting global variables.

However, I have a need to:


  1. refer to the matched string inside of the
    (?{ ... })
    block; and

  2. depending on its value, execute some arbitrary code



Desired Usage:

$input =~ m/ (foo)
(?{ if (defined (\1) { process(\1) } })
bar
/x;


Note: There may obviously be gazillion alternatives to achieving the same effect (TMTOWDI) but I'm interested only in the above style, for now. Hence, the post.

Answer

Here is an example.

perldoc perlre:

$^N contains whatever was matched by the most-recently closed group (submatch)

test_extended_re_code.pl

#!/usr/bin/env perl

use warnings;
use strict;

my @input = split /\n/, <<"END";
foo 123 bar
foo 456 bar
fo  789 bar
foo xyz bar
END

for my $input ( @input ) {
    $input =~ m/foo (\d+)(?{ process( $^N ) if $^N }) bar/;
}

sub process {
    my ($txt) = @_;
    print "Processing '$txt'\n";
}

Output

Processing '123'
Processing '456'