I've conditioned myself at this point to drop in a 'local $_;' whenever I use the <> operator in a function. But, today I was bitten by an oddity of $.. It was in very non-production code, but it's still worth knowing what's going on.

A simple example (what to look for: the line numbers in the warnings):

#!/usr/bin/perl use strict; use warnings; { open my $fh, '<', 'somefile' or die "Opening somefile for reading: + $!"; sub seeky { seek $fh, 0, 0 } } while (<DATA>) { chomp; my $line = $.; warn "Pre match: Line $. == $line\n"; next if /match/; seeky(); warn "Postmatch: Line $. != $line\n"; } __END__ foo match bar baz match bot

From perldoc perlvar, I think the following bit me:

When a line is read from a filehandle (via readline() or <> ), or when tell() or seek() is called on it, $. becomes an alias to the line counter for that filehandle.

I have two questions:

(UPDATE): Also, I noticed the section from perldoc perlvar about localizing $.:

Localizing $. will not localize the filehandle's line count. Instead, it will localize perl's notion of which filehandle $. is currently aliased to.

... but I couldn't seem to elicit any helpful effects by doing so. (figured a local $.; after the while(<DATA>) might keep it associated with *DATA.)


In reply to Localization gotcha? by benizi

Title:
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, details, 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, summary, 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.