Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Answer: How do I copy out the last line written in a file?

( #33035=categorized answer: print w/ replies, xml ) Need Help??

Q&A > files > How do I copy out the last line written in a file? contributed by Fastolfe

There are three commonly proposed methods to do this:

Read the entire file

@array = <FILE>; $last_line = $array[$#array];
This involves reading the entire file before examining the last line, which can be costly in memory and performance for large files.

Seek to the end and backtrack

seek(FILE, -81, 2); # 81 bytes from the end, which should +be enough @lines = <FILE>; $last_line = $lines[$#lines]; # similar to above, but we don't read +much
Use File::ReadBackwards
tie *FILE, File::ReadBackwards 'input_file'; while (<FILE>) { # line-by-line starting from the end }
This latter method is supposed to be efficient and fast, so I imagine it uses some variation of the seek() method above.

Comment on Answer: How do I copy out the last line written in a file?
Select or Download Code
Re: Answer: How do I copy out the last line written in a file?
by Anonymous Monk on May 03, 2007 at 01:56 UTC
    When a file is read into an array the last element in the array array-1 would give you what you are looking for. Shashidhar Iddamsetty
      When a file is read into an array the last element in the array array-1 would give you what you are looking for.

      To put it more clearly, and in actual Perl rather than some pseudo-language, the first example above, i.e.

      @array = <FILE>; $last_line = $array[$#array];

      could be rewritten like

      @array = <FILE>; $last_line = $array[-1];

      or even without creating an intermediate @array:

      my $last_line = (<FILE>)[-1];

      Incidentally, I put a my in front of that as a reminder of the good rule of always staying strict.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (10)
As of 2014-10-21 10:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (99 votes), past polls