in reply to Count number of lines?

Hello and welcome!

I can't really comment on good books for CGI programming as I only do a little of it, but try "CGI Programming with Perl" by Guelich, Gundavaram, and Birznieks. I like it and find it useful. However, being new to Perl, you may want to start with the Camel book or "The Perl Cookbook" by Christiansen and Torkington. All are O'Reilly books.

It sounds like you're asking how to "think Perl". That may take a while, but it sounds like you're going in the right direction: modify existing code. Here's how I might code the routine you're referring to:

sub how_many_lines { open I, 'users.dat' or warn("Couldn't open users.dat\n"), return; # That single statment will try to open "users.dat" # (it better be in the current directory). If that # fails, it'll print "Couldn't open users.dat" and # return undef (the undefined value) to the calling # routine. Yes, it's very terse, but that's part of # the power of Perl. my $lines; # Declare $lines local to this scope (the sub) ++$lines while <I>; # Read the entire file a line at a time, incrementing $lines # every time. close I; # Close the file handle $lines; # return the count to the caller. }
To answer your specific question, yes, there is an EOF test in Perl, but it's very rarely useful. The <> operator returns the undefined value at end-of-file, so an explicit test is usually redundant.

HTH, and good luck on your journey.

Replies are listed 'Best First'.
Re: Re: Count number of lines?
by ginocapelli (Acolyte) on Jun 20, 2001 at 07:44 UTC
    After the "open I, 'users.dat' or warn..." line, would this line flock the file?: flock I, 2; Thanks. slcpub@yahoo.ca
      Yes. I is a filehandle here, and can be used as the first argument to flock, as well as others like seek.

      BTW, to avoid having to remember that 2 is "exclusive lock", you can use symbolic names from the Fcntl module:

      use Fcntl; ... flock(I, LOCK_EX);
      See the perlfunc document for details.