문제

I am reading a text file into a SCALAR variable by using

open FILE, "<", $filename or print("Error opening $filename");
read FILE, my $buffer, -s $filename;    
close FILE;

Later on I am counting the number of lines in that SCALAR variable. How can I go to a specific line within that SCALAR variable without iterating through it?

도움이 되었습니까?

해결책

The answer to the question you originally posed is that unless you're dealing with a fixed-width file, you can't skip to a certain line without iterating somehow.

However, based on your comments, it seems that there's no need to read your entire file into a scalar in the first place. You can get both the second-to-last line and a total line count by simply iterating through the file like this:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my ($count, @previous);
while (<DATA>) {
    chomp;

    $count++;

    push @previous, $_;
    shift @previous if @previous > 2;
}

say "Count: $count";
say "Second-to-last line: $previous[0]";

__DATA__
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.

Output:

Count: 6
Second-to-last line: fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in

For simplicity, I used the special __DATA__ block instead of an external file. To read a file as above, do:

open my $fh, '<', '/path/to/file' or die "Failed to open file: $!";

while (<$fh>) {
    ...
}

close $fh;

Why is this better than reading the whole file into a scalar? If your file is large, reading the whole thing into memory all at once can be costly. Unless you have a good reason not to, it's generally better to read files one line at a time and process them as you go.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top