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

How would I convert the following piece of code to only join elements of the @CHOICE array that are defined?
$Command = join(' ', 'EXEC', $SPROC, join(', ', @CHOICE[1 .. $elements_in_array])) . '';

Replies are listed 'Best First'.
Re: Only joining elements of an array that are defined
by ayrnieu (Beadle) on Feb 14, 2006 at 10:27 UTC
    $cmd = join(' ', 'EXEC', $SPROC, join(', ', grep { defined $_ } @CHOICE));

    Updated.

Re: Only joining elements of an array that are defined
by GrandFather (Saint) on Feb 14, 2006 at 10:28 UTC

    I can't help you with that code, there are two joins and so many undefined variables that trying to understand what you intend is hopeless.

    However the following snippet may help resolve your problem:

    use strict; use warnings; my @array = (1, 2, undef, 4, 5, undef, undef, 8, 9); print join ' ', grep $_, @array;

    Prints:

    1 2 4 5 8 9

    DWIM is Perl's answer to Gödel

      Just a nit,

      grep $_, @array

      will not include false but defined values:

      use strict; use warnings; my @array = (1, 2, undef, 4, 5, 0, undef, 8, 9); print join (' ', grep $_, @array)."\n"; print join (' ', grep { defined } @array)."\n";
      Output
      1 2 4 5 8 9 1 2 4 5 0 8 9

      All dogma is stupid.

        Argh, I've not been bitten enough by that in real code. I have been bitten enough here by it that I should know better by now!

        Thanks for clarifying that for OP and the gentle reminder for me. :)


        DWIM is Perl's answer to Gödel
        grep defined, @array
      A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Only joining elements of an array that are defined
by tirwhan (Abbot) on Feb 14, 2006 at 10:28 UTC

    $Command = join(" ", grep { defined } ('EXEC',$PROC), join(', ', grep { defined } @CHOICE[1 .. $elements_in_array])) . '';

    All dogma is stupid.
    A reply falls below the community's threshold of quality. You may see it by logging in.