36

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.

Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108

4 Answers4

66
open my $file, '<', "filename.txt"; 
my $firstLine = <$file>; 
close $file;
wespiserA
  • 3,131
  • 5
  • 28
  • 36
7
open THEFILE, "<filename.txt";
$first_line = <THEFILE>;
close THEFILE;
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
3
open( my $file, "x.txt");
$line = <$file>;
Jakub M.
  • 32,471
  • 48
  • 110
  • 179
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).

illy
  • 1,578
  • 2
  • 9
  • 9
  • 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 Feb 20 '20 at 21:00