37

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 first line of a text file and extract the date from it.

new to perl.

0

4 Answers 4

68
open my $file, '<', "filename.txt"; 
my $firstLine = <$file>; 
close $file;
7
open THEFILE, "<filename.txt";
$first_line = <THEFILE>;
close THEFILE;
1
  • 18
    You should use lexical filehandles and three argument open.
    – TLP
    Commented Aug 11, 2011 at 15:18
3
open( my $file, "x.txt");
$line = <$file>;
1

... 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).

1
  • 2
    You might want to chomp $firstline; or the value could have a newline at the end and that might not be something you want.
    – joehep
    Commented Feb 20, 2020 at 21:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.