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.

In reply to Re: Matching against $_ behaves differently than matching against a named scalar? by rjt
in thread Matching against $_ behaves differently than matching against a named scalar? by nysus

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.