Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Use of uninitialized value $var in pattern match (m//)

by Athanasius (Archbishop)
on Apr 10, 2015 at 12:40 UTC ( [id://1123042]=note: print w/replies, xml ) Need Help??


in reply to Use of uninitialized value $var in pattern match (m//)

Hello CropCircle, and welcome to the Monastery!

This line:

my $var2 = $var =~ /red|green|blue/;

looks a bit strange to me. If $var contains 'xredy', for example, the match will succeed but $var2 will be set to 1 (“true”):

22:35 >perl -wE "my $var = 'xredy'; my $var2 = $var =~ /red|green|blue +/; say qq[|$var2|];" |1| 22:35 >

Is that really what you want? To set $var2 to the string that was matched, you need something like this:

22:25 >perl -wE "my $var = 'xredy'; my ($var2) = $var =~ /(red|green|b +lue)/; say qq[|$var2|];" |red| 22:30 >

The parentheses within the regex are for capturing, and the parentheses around $var put the match into list context. See perlretut#Extracting-matches. Or you can get the capture in $1:

22:38 >perl -wE "my $var = 'xredy'; $var =~ /(red|green|blue)/; my $va +r2 = $1; say qq[|$var2|];" |red| 22:38 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^2: Use of uninitialized value $var in pattern match (m//)
by CropCircle (Novice) on Apr 13, 2015 at 08:02 UTC

    Thanks a lot!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (4)
As of 2024-03-28 13:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found