in reply to What's like $+ but not gives the ordinal?
If you want the number of the backreference and you know in advance the number of possible backreferences, here's a quick hack:
#!/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; }
Update: Here's a much more robust example (though with no validation of arguments to the sub). Pass the string, the number of backreferences, and the regex and it will return to you the regex that matched:
#!/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; }
Of course, it returns the number of the backreference that matched first (i.e., if $2 matched first, it returns 2). It returns zero if no match is found. You'll have to test for this if you're using it as an array index unless $array[0] is a default.
Cheers,
Ovid
Vote for paco!
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (Ovid) Re: What's like $+ but not gives the ordinal?
by John M. Dlugosz (Monsignor) on Jun 28, 2001 at 01:51 UTC | |
by Ovid (Cardinal) on Jun 28, 2001 at 02:01 UTC | |
by John M. Dlugosz (Monsignor) on Jun 28, 2001 at 02:25 UTC |