Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Detecting last line and blank line

by davido (Archbishop)
on Nov 07, 2017 at 01:04 UTC ( #1202896=note: print w/replies, xml ) Need Help??


in reply to Detecting last line and blank line

The eof operator is useful here.

#!/usr/bin/env perl use strict; use warnings; my $fh = \*DATA; while(<$fh>) { chomp; print "<<<$_>>> is line $."; print ", and is the last line." if eof($fh); } continue { print ".\n"; } __DATA__ line 1 line 2 line 3

This produces the following output:

<<<line 1>>> is line 1. <<<line 2>>> is line 2. <<<line 3>>> is line 3, and is the last line.

My purpose in copying \*DATA into $fh was just so that the remainder of my example could operate on a filehandle that is closer to what one might see in typical code.


Dave

Replies are listed 'Best First'.
Re^2: Detecting last line and blank line
by haukex (Abbot) on Nov 07, 2017 at 05:27 UTC

    Anonymous Monk: eof is indeed useful, and just to add two points to what davido wrote, there are two peculiarities when it is used in while (<>) loops, including the implicit ones from the -n and -p command line switches. First, eof with and without empty parentheses is different - from its docs:

    In a while (<>) loop, eof or eof(ARGV) can be used to detect the end of each file, whereas eof() will detect the end of the very last file only.

    Second, davido's code example uses the line counter $., which does not get reset for each file in a while (<>) loop. To do that, you need close ARGV explicitly, that is:

    while (<>) { # your code here } continue { close ARGV if eof; # Not eof()! }

    This is normally done in a continue block because that way, it will still be executed even if you use next inside the loop.

    As for blank lines, I like to use next unless /\S/; to skip lines that contain only whitespace. That doesn't exactly meet your "0 characters" requirement - as LanX said, use eq to compare the line to "" after chomp (or to "\n" before).

    Although you don't say why you need to detect blank lines and the last line, note that setting $/=""; means files will be read in "paragraph mode", that is, records will be separated by one or more blank lines.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2017-12-17 23:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (466 votes). Check out past polls.

    Notices?