Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Can't do dereference when running code inserted inside regex

by Anonymous Monk
on Jan 16, 2022 at 06:59 UTC ( [id://11140491]=perlquestion: print w/replies, xml ) Need Help??

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

Latest Perl can't do dereference when running code inserted inside regex, this e.g.
use strict; my @dat=[qw(foo bar)]; for (@dat){ push (my @u, [$_->[0], $_->[1]]); 'foobar'=~/foo(?{ push (@u, [$_->[0], $_->[1]]) })/ } Can't use string ("foobar") as an ARRAY ref while "strict refs" in use + at (eval 25)[/usr/share/perl5/core_perl/perl5db.pl:741] line 2.

How come and to get fixing ? Because not involve inside regex,

use strict; my @dat=[qw(foo bar)]; for (@dat){ push (my @u, [$_->[0], $_->[1]]) }


Normal no error. Please help it.

Replies are listed 'Best First'.
Re: Can't do dereference when running code inserted inside regex
by dave_the_m (Monsignor) on Jan 16, 2022 at 09:42 UTC
    When executing a regex code block, perl temporarily alises $_ to the string currently being matched. So $_ is set to "foobar"

    Dave.

Re: Can't do dereference when running code inserted inside regex
by LanX (Saint) on Jan 16, 2022 at 11:59 UTC
    Dave is right

    And it's documented in perlre#(?{-code-}), right where it's supposed to be.

    Inside a (?{...}) block, $_ refers to the string the regular expression is matching against. You can also use pos() to know what is the current position of matching within this string.

    The solution is simple, use an explicit loop variable:

    for my $d (@dat){ push (my @u, [$d->[0], $d->[1]]); ...

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

      Dave, LanX are right.
      EXCELLENT ! Thanks billions.
Re: Can't do dereference when running code inserted inside regex
by AlexP (Pilgrim) on Jan 16, 2022 at 07:27 UTC

    I see error in your code:

    my @dat=[qw(foo bar)];

    You are trying to assign @var the reference to an array (not an array). You should:

    my @dat=qw(foo bar);

    Please, don't forget to use warnings pragma. It helps with these kinds of mistakes.

      Yes it looks strange, but that's what he wanted. Look at the dereference inside the loop.

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (4)
As of 2024-04-25 04:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found