in reply to Re: number of lists in array
in thread number of lists in array

Sorry if I sound dumb. Heh, that works. Would line counting in a file also work if I used foreach loops?

Replies are listed 'Best First'.
Re: Re: Re: number of lists in array
by rob_au (Abbot) on Nov 30, 2001 at 18:55 UTC
    Absolutely, sample code for a line count using a foreach loop might look like this:

    $/ = "\n"; my $count; open (FH, "myfile.text") || die "Cannot open file: $!"; $count++ foreach (<FH>); close FH;

     

    Update #1 - Also see the post from djw in this thread here.

    Update #2 - A piece of code designed to illustrate foreach really should use foreach and not while - Thanks Hofmator++

    Update #3 - And the snippets from Masem and davorg in this thread here and here are illustrative - Thanks especially to davorg for the $. suggestion.

     

    perl -e 's&&rob@cowsnet.com.au&&&split/[@.]/&&s&.com.&_&&&print'

      Of course you don't actually need to keep a count, as Perl does that for you in $..

      --
      <http://www.dave.org.uk>

      "The first rule of Perl club is you don't talk about Perl club."

      Or, probably faster, and with the benefit of having the file read into memory:
      my ( $count, @data ); open (FH, "myfile.txt") or die $!; $count = scalar (@data = <FH>); close FH;

      -----------------------------------------------------
      Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
      "I can see my house from here!"
      It's not what you know, but knowing how to find it if you don't know that's important

        I doubt it's efficient but this just looks too wierd not to mention.

        my $lines = do{ my $file_name = 'in.txt'; open my $fh, $file_name or die "$file_name: $!"; () = <$fh>; }; print $lines;



        HTH,
        Charles K. Clarkson
      Oh, and sorry to annoy you further, Rob, how does $. work? I could use the excuse that I'm living on the same side of the globe as you are...

        $. will always contain the current record number from the most recently read file handle.

        Full documentation for all of Perl's special variables can be found in perlvar.

        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you don't talk about Perl club."

        see perldoc perlvar or here.

        -- Hofmator