Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Refer by relative way to regex group (eg. the last one)

by Anonymous Monk
on Jan 19, 2022 at 01:01 UTC ( [id://11140600]=perlquestion: print w/replies, xml ) Need Help??

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

How to refer by relative way e.g. to get the last regex group from Perl code inserted inside regex, as
'foobar' =~ /(oo)(bar)(?{$word=${-1}})/

fails, word var. can't be bar ?

Replies are listed 'Best First'.
Re: Refer by relative way to regex group (eg. the last one)
by LanX (Saint) on Jan 19, 2022 at 01:22 UTC
      The \g{-1} syntax is interesting, I don't recall that one. When did it come about? (Of course, it's possible it's been around since Perl 4 and I just missed it :) )

      Mike

        Looks like 5.10 according to perl5100delta:

        Relative backreferences A new syntax "\g{N}" or "\gN" where "N" is a decimal integer a +llows a safer form of back-reference notation as well as allowing re +lative backreferences. This should make it easier to generate and emb +ed patterns that contain backreferences. See "Capture buffers" in perlre. (Yves Orton)

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.

        Grepping the perldelta* files for \\g lists perl5100delta, so likely the feature was introduced with Perl 5.10.0.

        Syntax::Construct to the rescue :-)

        map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

        Perl 5.9.5 if you want to be picky.

Re: Refer by relative way to regex group (eg. the last one)
by Anonymous Monk on Jan 19, 2022 at 16:10 UTC

    You do not say how your code fails, but if you add use strict; to your example you get

    $ perl -Mstrict -Mwarnings -e 'my $word; "foobar" =~ /(oo)(bar)(?{$word=${-1}})/'
    Can't use string ("-1") as a SCALAR ref while "strict refs" in use at -e line 1.
    

    Suggestions:

    $ perldoc -v '@-'
    $ perldoc -v '@+'
    

    Or, under at least Perl 5.10, you could use named captures.

      > Suggestions:

      sigh...

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

      update

      DB<29> "ab" =~ /^((.)(.))(?{say $+;say $^N; say "$1 $2 $3\n@{^CAPTUR +E}"})/ b ab ab a b ab a b

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11140600]
Approved by LanX
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (3)
As of 2024-04-24 20:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found