Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Detecting last line and blank line

by 1nickt (Monsignor)
on Nov 07, 2017 at 00:40 UTC ( #1202894=note: print w/replies, xml ) Need Help??


in reply to Detecting last line and blank line

If you know the number of lines, e.g if you get an array on standard input, or passed to a subroutine:

use strict; use warnings; use feature qw/ say /; chomp( my @lines = (<DATA>) ); my $num = @lines; my $count = 1; for my $line ( @lines ) { say "the last line is $line" if $num == $count++; } __DATA__ foo bar baz qux
$ perl 1202892.pl the last line is qux

If you don't know the number of lines, e.g. when reading a file that may be too large to slurp into memory all at once:

use strict; use warnings; use feature qw/ say /; # setting up the demo use Path::Tiny; my $file = Path::Tiny->tempfile; $file->spew("$_\n") for ('a' .. 'm'); ####### my $last_line; open my $fh, '<', $file or die "Cannot open file: $!"; while ( my $line = <$fh> ) { chomp $line; $last_line = $line; } say "the last line is $last_line"; __END__
$ perl 1202892-2.pl the last line is m

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Detecting last line and blank line
by Anonymous Monk on Nov 07, 2017 at 01:07 UTC

    I figured it out, before I saw you answer!

    But thanks anyway ;-) !

    (Ended up doing something similar to your last code)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1202894]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2018-07-19 15:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (411 votes). Check out past polls.

    Notices?