How to read only the first line of a file
I've been googling for a while, but I cannot find a function the read just first line of a file.
I need to read fi开发者_如何学Pythonrst line of a text file and extract the date from it.
new to perl.
open my $file, '<', "filename.txt";
my $firstLine = <$file>;
close $file;
open THEFILE, "<filename.txt";
$first_line = <THEFILE>;
close THEFILE;
open( my $file, "x.txt");
$line = <$file>;
... a modern and popular alternative:
use Path::Tiny;
(my $firstline) = path('filename.txt')->lines( { count => 1 } );
For more info https://metacpan.org/pod/Path::Tiny#lines-lines_raw-lines_utf8
Note: since ->lines
is returning a list, calling it without the brackets around $firstline
it will be assigned the number of lines which have been read from filename.txt
: 1 (or 0 if it's empty).
精彩评论