Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Looking for alternative syntax for assigning variables based on regex matches

by rsFalse (Chaplain)
on Mar 02, 2021 at 10:28 UTC ( #11129009=note: print w/replies, xml ) Need Help??


in reply to Looking for alternative syntax for assigning variables based on regex matches

With non-destructive /r modifier (and lookahead):
perl -wle '$foo = "a hello w"; $foo = $foo =~ s/(?=.*(hello)).*/$1/sr; + print $foo'
OUTPUT:
hello
And if you want only to use your capture, just:
...; print $foo =~ s/(?=.*(hello)).*/$1/sr;
In the later example a value of $foo didn't change.
*Updated

+one more way:
...; $foo =~ /hello(?{ $foo = $& })/; print $foo
Though it looks like bad practice to change a variable while it is in use.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11129009]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2022-08-17 01:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?