CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Read last line with ReadBackwards unless blank

 



Iconx
Novice

Feb 12, 2014, 2:14 PM

Post #1 of 5 (1012 views)
Read last line with ReadBackwards unless blank Can't Post

Hello,

I'm trying to write a script to read all files in a directory and then print the last line of each file unless its blank and I'm using File::ReadBackwards for this. How do I do that or is there a better way? Here's what I have so far:


Code
use strict; 
use File::ReadBackwards;
use File::Spec;

my $directory = 'readtest/reads';

opendir(DIR, $directory)|| die "cant open dir: $! \n";
my @files = readdir(DIR);

## Excludes paths . and ..
@files = File::Spec->no_upwards(@files);
foreach my $file (@files) {
chomp $file;
my $filename = "$directory/$file";

my $bw = File::ReadBackwards->new($filename) or die "cant read $filename: $!";
my $last_line=$bw->readline;
print "last_line is $last_line \n";
}


Thanks,

Iconx


Laurent_R
Veteran / Moderator

Feb 12, 2014, 2:44 PM

Post #2 of 5 (1009 views)
Re: [Iconx] Read last line with ReadBackwards unless blank [In reply to] Can't Post

Yes, the File::ReadBackwards is probably the best way.

Other possible ideas, much less likely to be what you need:
- Loading into an array the output of the tail fonction under Unix/Linux;
- if the file is small enough, slurping it into an array and taking the last record;
- reading though the file and always remembering the previous line;
- reading the file stats (especially the size) and using the seek function to get near the end (very feasible if you have a good idea of the usual line length).


Iconx
Novice

Feb 13, 2014, 8:57 AM

Post #3 of 5 (994 views)
Re: [Laurent_R] Read last line with ReadBackwards unless blank [In reply to] Can't Post

Yea ok so I've got the code as far as reading the last line but now what do I do to make it so incase the line is blank read back 2 lines with this module?


FishMonger
Veteran / Moderator

Feb 13, 2014, 9:55 AM

Post #4 of 5 (988 views)
Re: [Iconx] Read last line with ReadBackwards unless blank [In reply to] Can't Post

Did you try adding one or more $bw->readline; statements to move the the desired line?

Another option would be to use the Tie::File module instead of File::ReadBackwards and then access the desired array element.
http://search.cpan.org/~toddr/Tie-File-0.98/lib/Tie/File.pm


Laurent_R
Veteran / Moderator

Feb 13, 2014, 10:06 AM

Post #5 of 5 (986 views)
Re: [Iconx] Read last line with ReadBackwards unless blank [In reply to] Can't Post

Just keep reading backward until you find a non empty line.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives