Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

'defined' function

by Anonymous Monk
on Jun 13, 2003 at 10:36 UTC ( #265632=perlquestion: print w/replies, xml ) Need Help??

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

Hi Monks, I am pushing certain elements of one array into another array but the program is struggling if/when these elements don't exist. I thought about using the defined function for this but wondered if there was a quick way to check for each element and then if it is defined, push it into the array. Thanks ;->
if ($p ==1) { push @points, "$peaks[7] $peaks[8] $peaks[9] $peaks[10] $peaks[11] $ +peaks[12] $peaks[13]"; }

Replies are listed 'Best First'.
Re: 'defined' function
by broquaint (Abbot) on Jun 13, 2003 at 10:43 UTC
    It depends on how you want to deal with the empty elements, but a grep should do the job there e.g
    push @points, join ' ', grep defined, @peaks[7 .. 13];
    See. the grep docs for more info.
    HTH

    _________
    broquaint

Re: 'defined' function
by Zaxo (Archbishop) on Jun 13, 2003 at 10:51 UTC

    This assumes that the elements you want to push are at the end of the array, and that undefined ones come from the array being short.

    if ($p == 1 ) { push @points, @peaks[7..$#peaks]; }
    That makes use of an array slice to avoid the repetitive list of elements. The $#peaks variable is a builtin carrying the last index of the array.

    (Update) The grep solutions are more general since they also work for arrays with holes in them. The last index trick is useful with them, too.

    After Compline,
    Zaxo

Re: 'defined' function
by ChOas (Curate) on Jun 13, 2003 at 10:48 UTC
    Something like this ? :
    push @points,grep {defined} @peaks[7,8,9,10,11,12,13];
    OR (as you seem to have written:)
    push @points,join " ",grep {defined} @peaks[7,8,9,10,11,12,13]

    -edit- too late :)
    GreetZ!,
      ChOas

    print "profeth still\n" if /bird|devil/;
Re: 'defined' function
by EvdB (Deacon) on Jun 13, 2003 at 10:51 UTC
    This should do it:
    # Test me - i do not have the data. my $string; for (7..13) { next unless defined $peaks[$_]; $string = join ' ', $string, $peak[$_]; } push @points, $string;

    --tidiness is the memory loss of environmental mnemonics

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://265632]
Approved by EvdB
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2019-06-19 05:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Is there a future for codeless software?



    Results (84 votes). Check out past polls.

    Notices?
    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!