Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

Scotmonk:

If the file is small enough that it fits comfortably in memory, you could just read the whole thing and then reverse it, like this:

# foo.pl - print a file in reverse use strict; use warnings; my $FName = shift // die "Expected a filename!"; open my $FH, '<', $FName or die "Can't open $FName: $!\n"; # Read all the lines my @lines = <$FH>; # Reverse the order @lines = reverse @lines; for my $line (@lines) { print $line; }

When I run it on itself, I get:

$ perl foo.pl foo.pl } print $line; for my $line (@lines) { @lines = reverse @lines; # Reverse the order my @lines = <$FH>; # Read all the lines open my $FH, '<', $FName or die "Can't open $FName: $!\n"; my $FName = shift // die "Expected a filename!"; use warnings; use strict; # foo.pl - print a file in reverse

Sometimes a file is too big to handle that way, though that's increasingly rare with modern computers. But if so, you could always use a program (such as tac) that will reverse the file for you, and then you can process the file in order in your code.

For one-off jobs, that's the way I'd go. But if you always need to process the files in reverse, I'd use the File::Backwards module that stevieb suggested.

...roboticus

When your only tool is a hammer, all problems look like your thumb.


In reply to Re: Reading the contents of a file from the bottom up by roboticus
in thread Reading the contents of a file from the bottom up by Scotmonk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-19 12:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found