in reply to Re: Only joining elements of an array that are defined
in thread Only joining elements of an array that are defined

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.

Replies are listed 'Best First'.
Re^3: Only joining elements of an array that are defined
by GrandFather (Saint) on Feb 14, 2006 at 10:38 UTC

    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
Re^3: Only joining elements of an array that are defined
by Anonymous Monk on Feb 14, 2006 at 10:49 UTC
    grep defined, @array

      <shrug/>Whatever works for you. I find that always using the block form of grep and map is a lot clearer for the compiler as well as human reader, and can prevent mistakes for more complicated expressions, at the cost of one extra character. So unless you're golfing it's probably better to stick with that.


      All dogma is stupid.

        The BLOCK form however does incur a bit more overhead since it has to do all the steps incurred entering and exiting a block. If it's done once, you're probably not going to notice it; if it's a statement you're executing each line for your 1G data file it may add up. Granted it's relatively small and may have been optimized in recent versions, but be aware of the overhead if you're looking for somewhere to shave a few microseconds off after you benchmark (of course always benchmark :).

        I disagree. If EXPR is simple enough, as in this case, then at least for me it is much easier to read. I'm just used to it. Of course should it grow complex enough, then it would soon become a pita, thus I would prefer a BLOCK instead. I don't have the slightest idea about the compiler - and I don't care much.

      grep length,

      Is better, because we don't want extra spaces for empty lines

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