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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Detecting last line and blank line
by Anonymous Monk on Nov 07, 2017 at 01:07 UTC |