?
Solved

Easy way to reverse file read in perl?

Posted on 2009-02-15
7
Medium Priority
?
653 Views
Last Modified: 2012-05-06
I would like to know if there is an easy way to read a file in reverse.

In other words, read from the end of the file to the start of the file instead of start to end. I feel it would be more efficient rather than loading it into an array and then reversing it in memory, to just load it already reversed.
open(R,"$my_file");
# read file in reverse with <R>
close(R);

Open in new window

0
Comment
Question by:dr34m3rs
7 Comments
 
LVL 85

Accepted Solution

by:
ozo earned 2000 total points
ID: 23646824
print reverse <R>;


or
open my $rev, '<:reverse', $file;

or
0
 
LVL 85

Expert Comment

by:ozo
ID: 23646830
or

use File::ReadBackwards ;
0
 
LVL 85

Expert Comment

by:ozo
ID: 23646839
or  
 use Tie::File;
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:masheik
ID: 23646849
hi, try this code
open( FILE, "<$file_to_reverse" )
  or die( "Can't open file file_to_reverse: $!" );
 
@lines = reverse <FILE>;
 
foreach $line (@lines)
 {
  # do something with $line
 }

Open in new window

0
 
LVL 28

Expert Comment

by:FishMonger
ID: 23646951
0
 
LVL 1

Author Comment

by:dr34m3rs
ID: 23646992
Thanks!
0
 
LVL 1

Author Closing Comment

by:dr34m3rs
ID: 31547174
Perfect, thanks.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many time we need to work with multiple files all together. If its windows system then we can use some GUI based editor to accomplish our task. But what if you are on putty or have only CLI(Command Line Interface) as an option to  edit your files. I…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Six Sigma Control Plans
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question