Harry Harry - 1 year ago 79
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
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) } })

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 Source

Here is an example.

perldoc perlre:

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


#!/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

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

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


Processing '123'
Processing '456'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download