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!
In reply to Re: Detecting last line and blank line
by 1nickt
in thread Detecting last line and blank line
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |