General
Showing results for 
Search instead for 
Do you mean 

Substitution for tail -1 in a Perl script

SOLVED
Go to Solution
Occasional Contributor

Substitution for tail -1 in a Perl script

I m writing this script and I 've encountered
a problem in substititing tail -1 in a Perl script to get the last line in a file. SOS please.

My script is as follows:

#!/usr/local/bin/perl
open(INP,"/export/home/soglesby/gents_processed");
while() {
chomp;
next unless /dat/;
@a=split('\s+',$_);
$a[8]=~s/\.dat//g;
$a[8]=~s/return_//g;
#system "tail -1" I've tried this
print
print "\n";
}
1 ACCEPTED SOLUTION
Acclaimed Contributor Acclaimed Contributor

Re: Substitution for tail -1 in a Perl script

Hi Stephen:

Onw way to accomplish this is to add a test for end-of-file like this:

while () {
next if !eof;
chomp;
...

This would process *only* the last line.

Regards!

...JRF...
5 REPLIES
Acclaimed Contributor Acclaimed Contributor

Re: Substitution for tail -1 in a Perl script

Hi Stephen:

Onw way to accomplish this is to add a test for end-of-file like this:

while () {
next if !eof;
chomp;
...

This would process *only* the last line.

Regards!

...JRF...
Highlighted
Occasional Contributor

Re: Substitution for tail -1 in a Perl script

Thanks, sounds like a great idea!
Honored Contributor Honored Contributor

Re: Substitution for tail -1 in a Perl script

One linear as,

# perl -ne 'print if eof'

hth.
Easy to suggest when don't know about the problem!
Honored Contributor Honored Contributor

Re: Substitution for tail -1 in a Perl script

#!/usr/bin/perl -w
# example for files with max line lengths < 400, but it's adjustable
# usage tailz filename numberoflines
use strict;

die "Usage: $0 file numlines\n" unless @ARGV == 2;
my ($filename, $numlines) = @ARGV;

my $chunk = 400 * $numlines; #assume a <= 400 char line(generous)

# Open the file in read mode
open FILE, "<$filename" or die "Couldn't open $filename: $!";
my $filesize = -s FILE;
if($chunk >= $filesize){$chunk = $filesize}
seek FILE,-$chunk,2; #get last chunk of bytes

my @tail = ;
if($numlines >= $#tail +1){$numlines = $#tail +1}
splice @tail, 0, @tail - $numlines;

print "@tail\n";
exit;

=============================

# ./tailz.pl
Usage: ./tailz.pl file numlines

-Arun
"A ship in the harbor is safe, but that is not what ships are built for"
Honored Contributor

Re: Substitution for tail -1 in a Perl script

chomp (my $last_line = ()[-1]);

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn