Re: Substitution for tail -1 in a Perl script (296 Views)
Reply
Occasional Contributor
Posts: 8
Registered: ‎09-16-2005
Message 1 of 6 (296 Views)
Accepted Solution

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";
}
Acclaimed Contributor
Posts: 21,184
Registered: ‎07-06-2000
Message 2 of 6 (296 Views)

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...
Occasional Contributor
Posts: 8
Registered: ‎09-16-2005
Message 3 of 6 (296 Views)

Re: Substitution for tail -1 in a Perl script

Thanks, sounds like a great idea!
Honored Contributor
Posts: 4,030
Registered: ‎06-09-2004
Message 4 of 6 (296 Views)

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
Posts: 4,194
Registered: ‎04-07-2005
Message 5 of 6 (296 Views)

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
Posts: 6,191
Registered: ‎10-13-1997
Message 6 of 6 (296 Views)

Re: Substitution for tail -1 in a Perl script

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

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.