Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Matching against $_ behaves differently than matching against a named scalar?

by Marshall (Canon)
on Apr 23, 2020 at 01:28 UTC ( [id://11115919]=note: print w/replies, xml ) Need Help??


in reply to Matching against $_ behaves differently than matching against a named scalar?

As an general practice, I do not fiddle around with $1 and $2. I use list context to assign these variables to specific names. This avoids some complications and is not "expensive" in terms of CPU..
use strict; use warnings; while (<DATA>) { if ( (my $first,my $second) = /^([^ ]+) ([^ ]+)/ ) { print "$first $second\n"; } } #prints: hello one __DATA__ hello one two three kjsf kjsd kjd
Now of course the regex could be written differently. This means the same thing.
use strict; use warnings; while (<DATA>) { if ( (my $first,my $second) = /^(\S+)\s+(\S+)/ ) #ok, allow an extra + spaces between tokens { print "$first $second\n"; } } #prints: hello one __DATA__ hello one two three kjsf kjsd kjd

Replies are listed 'Best First'.
Re^2: Matching against $_ behaves differently than matching against a named scalar?
by Anonymous Monk on Apr 23, 2020 at 02:23 UTC

    (my $first,my $second) = /^([^ ]+) ([^ ]+)/

    Eeew :P

    if( my( $first, $last) = $line =~ /^([^ ]+) ([^ ]+)/ ){ }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-04-19 22:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found