I guess the secret to it is in skipping the things in the middle.
1. Open the file
2. yadda yadda yadda
3. First and last line.
my $first;
my $last;
{
open(my $fh, '<', 'file')
or die("Unable to open input file: $!\n");
while (<$fh>) {
$first = $_ if not defined $first;
$last = $_;
}
}
or
use File::ReadBackwards ();
my $first;
my $last;
{
open(my $fh, '<', 'file')
or die("Unable to open input file: $!\n");
$first = <$fh>;
}
{
my $fh = File::ReadBackwards->new('file')
or die("Unable to open input file: $!\n");
$last = $fh->readline();
}
or
my $first;
my $last;
{
open(my $fh, '<', 'file')
or die("Unable to open input file: $!\n");
($first, $last) = (<$fh>)[0, -1];
}
perl -e "@l = <>; print 'first : ', $l[0], 'last : ', $l[$#l];" filename
perl -e "$first = <>; while($line = <>) { $last = $line; }; print 'first : ', $first, 'last : ', $last;" filename
It's still not recommended for larges files because the entire file is being read. If you have a 4gbyte file and your I/O subsystem is only able to read 10 Mbytes/second you're going to take 400 seconds to get the answer.
Or use File::ReadBackwards as ikegami suggests.
- seek to the end of the file
- search for the line terminator of the line before the last
- read from the position of the character after the line terminator to the end of file.
my $first = `head -1 $filename`; my $second = `tail -1 $filename`;If you happened to want a solution regardless of the implementation (ie Perl or not), and were ignorant of the head and tail programs, then learn to use those.
my ( $first, $last ) = `head -1 $filename && tail -1 $filename`;
perlmonks.org content © perlmonks.org and Anonymous Monk, Corion, Fletch, graff, holli, ikegami, malduarte, suaveant, zshzn
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03