Ignore undef elements for array count

Discussion in 'Perl Misc' started by David, Nov 11, 2004.

  1. David

    David Guest

    Dear all,

    How does one get the number of non-empty elements in an array? The
    following snippet prints '3', I only want to count the non-empty
    elements.

    Thanks!

    #!/usr/bin/perl

    use strict;

    local $\ = "\n";
    my @arr = qw ( sissors paper undef );
    print scalar @arr;
     
    David, Nov 11, 2004
    #1
    1. Advertisements

  2. David wrote:
    > How does one get the number of non-empty elements in an array? The
    > following snippet prints '3', I only want to count the non-empty
    > elements.
    >
    > local $\ = "\n";
    > my @arr = qw ( sissors paper undef );
    > print scalar @arr;


    But this array does not contain any undefined elements. The first element
    contains the text 'sissors', the second the text 'paper', and the third the
    text 'undef', all three of them well defined strings.

    If you are talking about actual undefined values then just filter for
    defined values before counting them:

    print scalar grep defined, @arr;

    jue
     
    Jürgen Exner, Nov 11, 2004
    #2
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ankur Bulsara
    Replies:
    0
    Views:
    554
    Ankur Bulsara
    Apr 23, 2004
  2. P
    Replies:
    1
    Views:
    1,380
    Joe Kesselman
    Jul 7, 2006
  3. Rob Meade
    Replies:
    6
    Views:
    466
    Rob Meade
    Mar 1, 2004
  4. Dan Kohn
    Replies:
    6
    Views:
    585
    Robert Klemme
    Dec 28, 2013
  5. Yehuda Berlinger

    Using undef as an array subscript

    Yehuda Berlinger, Jul 1, 2003, in forum: Perl Misc
    Replies:
    8
    Views:
    261
    Greg Bacon
    Jul 1, 2003
  6. hara
    Replies:
    4
    Views:
    288
    David Squire
    May 25, 2006
  7. Tim McDaniel

    undef($foo) versus $foo = undef()?

    Tim McDaniel, Aug 19, 2009, in forum: Perl Misc
    Replies:
    6
    Views:
    361
    Peter J. Holzer
    Aug 19, 2009
  8. Rafal Konopka

    Count elements in an array

    Rafal Konopka, Mar 13, 2005, in forum: Javascript
    Replies:
    9
    Views:
    227
    Rafal Konopka
    Mar 17, 2005
Loading...