in reply to (Ovid) Re: What's like $+ but not gives the ordinal?
in thread What's like $+ but not gives the ordinal?

I don't understand why you need to localize the backref variables. Also, you're finding the first capture, not the last.

Here is a way that finds the max by itself, as implied by another message on this thread:

sub last_paren_match_ordinal() { my $n= scalar @+; # gives number of captures present. while ($n) { no strict 'refs'; last if defined $$n; --$n; } return $n; }
In your new code, you are localizing the same name as you are my-ing. What's that for? It's not even used inside the block where it's localized.

—John

Replies are listed 'Best First'.
(Ovid) Re(3): What's like $+ but not gives the ordinal?
by Ovid (Cardinal) on Jun 28, 2001 at 02:01 UTC

    John, this stuff gets a bit tricky because what I've done is write a code generator.

    I don't understand why you need to localize the backref variables.

    Because if the match fails on the current attempt, but it succeeded on a previous attempt, the backref variables ($1, $2, etc) will contain the values from the previous match. The following code demonstrates this:

    my $string = '1234'; $string =~ /(2)/; $string =~ /(a)/; print $1;
    Also, you're finding the first capture, not the last.

    I misread your post then. Make the following change:

    - for ( 1 .. $num_refs ) { + for ( $num_refs .. 1 ) {
    Here is a way that finds the max by itself...

    I didn't know about the @+ variable :)

    In your new code, you are localizing the same name as you are my-ing.

    Actually, I'm not. Before the eval statement, add the statement print $code;. That will show you what's going on. The HERE document is a scalar containing generated code to be evaled. That's all.

    As I mentioned, my code is probably not worth the effort as I did not know about @+. :)

    Update 2: Duh! Of course $num_refs .. 1 isn't going to work. Sigh.

    Cheers,
    Ovid

    Vote for paco!

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      I guess there is a lot of powerful stuff going on there that I don't follow.

      - for ( 1 .. $num_refs ) { + for ( $num_refs .. 1 ) {
      That's not what happens when I try it. For example,
      perl -e "$n=5; for($n..1) { print }"
      does not print the reverse of
      perl -e "$n=5; for(1..$n) { print }"