Operating System - HP-UX
1748169 Members
4224 Online
108758 Solutions
New Discussion юеВ

Re: Substitution for tail -1 in a Perl script

 
SOLVED
Go to solution
Stephen_175
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";
}
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

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...
Stephen_175
Occasional Contributor

Re: Substitution for tail -1 in a Perl script

Thanks, sounds like a great idea!
Muthukumar_5
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!
Arunvijai_4
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"
H.Merijn Brand (procura
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