Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I am a Perl newbie. How could I find out the number of lists in an array, returned as a string? This could be very useful in counting the number of lines in a file, for instance.

Replies are listed 'Best First'.
Re: number of lists in array
by davorg (Chancellor) on Nov 30, 2001 at 19:16 UTC

    Just wanted to give my pedantic side a bit of an outing...

    An array will always contain exactly one list.

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

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

Re: number of lists in array
by rob_au (Abbot) on Nov 30, 2001 at 18:40 UTC
    Maybe I am misinterpreting this question, but the perlfunc:scalar function should do this for you:

    use strict; my @a = ( '1', '2', '3', '4', '5' ); print scalar @a, "\n";

     

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

      Sorry if I sound dumb. Heh, that works. Would line counting in a file also work if I used foreach loops?
        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'

Re: number of lists in array
by djw (Vicar) on Nov 30, 2001 at 18:57 UTC
    faq_monk is a brilliant monk - here is one way to find number of lines in a file. This way protects you from some assumptions about your file not having a newline character, and you getting one less line than expected.

    djw