Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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

by rjt (Curate)
on Apr 20, 2020 at 20:28 UTC ( #11115843=note: print w/replies, xml ) Need Help??

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

You have a couple of suggestions already, plus the explanation for why $1 and $2 survive successive loop iterations. Here is how I would modify the code:

use 5.010; use autodie; open my $fh, '<', 'text.txt'; while (<$fh>) { my @words = split /\s/; say "@words[0..1]" if @words >= 2; }

Note the use of autodie to avoid having to do explicit error checking on open or reads. Also note the use of three-argument open, which is an important security best-practice. Not necessary in your example, since your filename is a literal, but it's a good habit to get into.

It looks like you're really just splitting words on whitespace, so split seemed more natural and expressive to me. Maybe this was a contrived example to show the regex behaviour, and your real code really needs the regex, but for what's in front of me, split would be my choice.

Finally, I like say, but you can of course use print, and drop the 5.010 requirement if you are going for maximum backward compatibility.

Edit: My actual final word is, thanks for teaching your kid some Perl!

use strict; use warnings; omitted for brevity.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2023-04-01 19:43 GMT
Find Nodes?
    Voting Booth?

    No recent polls found