Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Printing Last Element of a line using perl memory?

by nvivek (Vicar)
on Feb 15, 2013 at 06:26 UTC ( #1018847=note: print w/ replies, xml ) Need Help??


in reply to Printing Last Element of a line using perl memory?

If we want to print last line of any file, we can use the following code.

use strict; use warnings; # open the file using _ to avoid multiple system calls invoked by perl open _,"filename"; # reading all lines from a file and store it into @lines array my @lines=<_>; # printing the last line of a file in @lines by $#lines => last index +of the array print @lines[$#lines];


Comment on Re: Printing Last Element of a line using perl memory?
Download Code
Re^2: Printing Last Element of a line using perl memory?
by dave_the_m (Parson) on Feb 15, 2013 at 12:53 UTC
    That code is bad in so many ways.
    # open the file using _ to avoid multiple system calls invoked by perl open _,"filename";
    This is complete nonsense. Using an underscore as the filename makes no difference to the execution, but makes the code harder to understand. Also, you should normally use lexical filehandles. Lastly, there's no error checking on the open.

    my @lines=<_>;
    This will crash with memory exhaustion if the file is too large
    @lines[$#lines];
    With warnings enabled, that will give:
    Scalar value @lines[$#lines] better written as $lines[$#lines]
    But could be even better written as
    $lines[-1]

    Dave.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1018847]
help
Chatterbox?
and the web crawler heard nothing...

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

    For retirement, I am banking on:










    Results (106 votes), past polls