#!/usr/bin/perl -w use strict; my $string = 'abcbar'; my $sub = get_backref( $string ); print $sub; sub get_backref { my $string = shift; my $regex = '(foo)|(bar)|(baz)'; my $backref = 0; # This is the number of possible backreferences # It's easier to set than generate dynamically my $limit = 3; local ( $1, $2, $3 ); $string =~ /$regex/; for ( 1 .. $limit ) { no strict 'refs'; $backref = $_, last if defined $$_; } return $backref; } #### #!/usr/bin/perl -w use strict; my $string = 'abcbar'; my $sub = get_backref( $string, 3, '(foo)|(bar)|(baz)' ); print $sub; sub get_backref { my ( $string, $num_refs, $regex ) = @_; my $backref = 0; # This is the number of possible backreferences # easier to set than count my $local_brefs = ''; for ( 1 .. $num_refs ) { $local_brefs .= "\$$_,"; } chop $local_brefs; my $code = <<" END_OF_CODE"; local ( $local_brefs ); \$string =~ /$regex/; for ( 1 .. $num_refs ) { no strict 'refs'; \$backref = \$_, last if defined \$\$_; } END_OF_CODE eval $code; return $backref; }