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. Advertising

  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. Advertising

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. Rob Meade
    Replies:
    6
    Views:
    260
    Rob Meade
    Mar 1, 2004
  2. Dan Kohn
    Replies:
    6
    Views:
    290
    Robert Klemme
    Dec 28, 2013
  3. Yehuda Berlinger

    Using undef as an array subscript

    Yehuda Berlinger, Jul 1, 2003, in forum: Perl Misc
    Replies:
    8
    Views:
    121
    Greg Bacon
    Jul 1, 2003
  4. hara
    Replies:
    4
    Views:
    151
    David Squire
    May 25, 2006
  5. Tim McDaniel

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

    Tim McDaniel, Aug 19, 2009, in forum: Perl Misc
    Replies:
    6
    Views:
    136
    Peter J. Holzer
    Aug 19, 2009
Loading...

Share This Page