Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I'm testing out some experimental regex features (perlre/perlretut), and I'm wondering why this doesn't match
for ( '<1>', # want match '<<2>>', # want match '<<3>', # want fail '<<<4>>', # want fail '<<5>>>>', # want fail ){ use vars qw' $LEN '; print "$_\n"; print " $_\n" for m( (?<! < ) # no preceeding < (?><+)(?{ $LEN = length $^N; }) ( [^><]* ) (?(?{ $LEN > 0 })(??{ '>' x $LEN })) (?! > ) # no following > )x; print " LEN = $LEN\n"; } __END__ <1> LEN = 0 <<2>> LEN = 0 <<3> LEN = 0 <<<4>> LEN = 0 <<5>>>> LEN = 0

Replies are listed 'Best First'.
Re: experimental regex (?(?{code}) conditional (??{ 'code' }) )
by ikegami (Patriarch) on Nov 12, 2010 at 15:11 UTC

    You don't have any captures before your use of $^N, so it's always undef when you use it. Change

    (?><+)

    to

    ((?><+))

    By the way,

    use vars qw' $LEN ';
    would be better as
    local our $LEN;
Re: experimental regex (?(?{code}) conditional (??{ 'code' }) )
by JavaFan (Canon) on Nov 12, 2010 at 17:10 UTC
    use 5.010; use strict; use warnings; while (<DATA>) { chomp; say "$_ ", /(<+)[^<>]*(>+)(*COMMIT)(?(?{length($1) == length($2)})|(*FAIL +))/ ? "matches" : "does not match"; } __DATA__ <1> <<2>> <<3> <<<<4>> <<5>>>>
    Output:
    <1> matches <<2>> matches <<3> does not match <<<<4>> does not match <<5>>>> does not match
Re: experimental regex (?(?{code}) conditional (??{ 'code' }) )
by Marshall (Canon) on Nov 12, 2010 at 16:36 UTC
    If you have a token like this, then regex is not the right tool. Use tr to count < and > and just see if they are equal in number.
    #!/usr/bin/perl -w use strict; for ( '<1>', # want match '<<2>>', # want match '<<3>', # want fail '<<<4>>', # want fail '<<5>>>>', # want fail ) { my $left = tr/<//; my $right = tr/>//; if ($left == $right) { print "$_ match\n"; } else { print "$_ fail\n"; } } __END__ Prints: <1> match <<2>> match <<3> fail <<<4>> fail <<5>>>> fail
      If you have a token like this, then regex is not the right tool.

      Sure, but perl regex definitely is the right tool for the job.

      FYI, the topic at hand is perl experimental feature (?(?:{code}) (??{'code'})), stick to it :)

        Can you some give examples that illustrate your point better? Meaning the need for more complex syntax, ie where more straightforward approaches fail to deliver the desired result?