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 22, 2020 at 22:23 UTC

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

    Eeew :P

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