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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |