Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

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

by Fastolfe (Vicar)
on Sep 19, 2000 at 01:53 UTC ( #33035=categorized answer: print w/replies, xml ) Need Help??

Q&A > files > How do I copy out the last line written in a file? - Answer 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.

Replies are listed 'Best First'.
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 all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2016-12-03 14:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (56 votes). Check out past polls.