On Sun, Oct 14, 2001 at 01:00:15PM +0200, allan wrote:
> is it somehow possible - while slurping a file - to still keep track of
> the line numbers?
Not with the $. variable. $. holds the number of chunks read, which is the
number of lines only if $/ is "\n".
> something like:
>
> #!/usr/bin/perl -w
>
> my $file = "1.txt";
> # 11 - line number 1
> # 22 - line number 2
> # 55 - line number 3
> # 77 - line number 4
>
> open FILE, $file or die $!;
> local $/;
> $txt = <FILE>;
>
> if ($txt =~ /55$/m) {
> print $.;
> # should print 3
> }
If you want to slurp in the file, you'll have to count the lines yourself.
Here's one way to do it, using the same code structure.
#!/usr/bin/perl -w
my $file = "1.txt";
# 11 - line number 1
# 22 - line number 2
# 55 - line number 3
# 77 - line number 4
open FILE, $file or die $!;
local $/;
$txt = <FILE>;
if ($txt =~ /55$/mg) {
print substr($txt, 0, pos($txt)) =~ tr/\n// + 1;
}
__END__
Note that you will need to reset pos($txt) if the next match should start
at the beginning of the string.
Ronald