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