Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

How do I print a partial array?

by shampoo7 (Initiate)
on Jun 13, 2001 at 21:38 UTC ( [id://88137]=perlquestion: print w/replies, xml ) Need Help??

shampoo7 has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

I am trying to print an array. But not all the elements are intialize. i.e.
@b[0]=c; @b[1]=undef; @b[3]=undef; @b[4]=a;
so when i use print "@b", I want only @b[0] and @b[4] to be printed. How do I skip the undef elements?

Edited 2001/06/13 by Ovid

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I print a partial array?
by MeowChow (Vicar) on Jun 13, 2001 at 22:21 UTC
Re: How do I print a partial array?
by Albannach (Monsignor) on Jun 13, 2001 at 21:49 UTC
    You can test whether an element has been defined with the sensibly named defined function, so one way might be something like:
    for my $element (@a) { print $element if defined($element); }
Re: How do I print a partial array?
by Sifmole (Chaplain) on Jun 13, 2001 at 22:15 UTC
    print map { defined $_ ? $_ : ''; } @b; would be one way.
Re: How do I print a partial array?
by dragonchild (Archbishop) on Jun 13, 2001 at 21:54 UTC
    If you already know what elements you want to print, then doing something like print @b[0,4,6..8], "\n"; will print just those elements. This is called an array slice.
Re: How do I print a partial array?
by Bloodelf (Beadle) on Jun 19, 2001 at 01:08 UTC
    Another way....

    foreach ( @b ) { print "$_\n" if defined $_; }

    Edited by davido: Added "defined" to conditional so that elements containing '0' would still print, while undefined elements are skipped.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://88137]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2024-07-17 12:41 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.