Ignore undef elements for array count

D

David

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;
 
J

Jürgen Exner

David said:
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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top