Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Determining what line a filehandle is on

by wog (Curate)
on Jul 06, 2001 at 00:06 UTC ( [id://94246]=note: print w/replies, xml ) Need Help??


in reply to Determining what line a filehandle is on

The $. variable described in perlvar does exactly this. Or you could keep your own variable to count lines and increment it yourself.

I hope that you are checking the return value of open in your real code. (e.g. open FILE, "file.txt" or die "opening file.txt for reading: $!\n";).

Replies are listed 'Best First'.
Re^2: Determining what line a filehandle is on
by tadman (Prior) on Jul 06, 2001 at 00:45 UTC
    More specifically:
    my $line = 0; my $file = "file.txt"; open (FILE, $file) || die "Could not open $file\n"; while (<FILE>) { print "I am on line ", ++$line, "\n"; } close (FILE);
      "More specifically"? What's wrong with using $.?
        There's nothing "wrong" with using $. since it accurately represents the line number read of the last file-handle read. You can even track more than one file at the same time:
        open (A, "ls|"); open (B, "ls|"); while (<A>) { print "A: $. "; <B>;<B>; print "B: $. "; } close (A); close (B);
        Which returns the output:
        A: 1 B: 2 A: 2 B: 4 A: 3 B: 6 A: 4 B: 8 A: 5 B: 10
        However, $. is what I would call a "magical" Perl variable because it comes from nowhere and has no inherent meaning. With English, it is $INPUT_LINE_NUMBER, and with IO::Handle you can use the method input_line_number, but the $INPUT_LINE_NUMBER variable is still "magical", and the IO::Handle system just makes things more difficult to implement.

        "Magical" variables, or those that are effectively, though not intuitively, linked to another variable or action are certainly able to be used, but the issue I have with them is that to the average programmer, especially one not intimately familar with Perl, is that they don't make any sense. Using them on a quick hack is one thing, but using them on a program that might have to be maintained by others is a counterproductive form of obfuscation.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2024-03-29 09:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found