in reply to Foreach syntax

If you want it all on one line:

for my $p9 ( grep { $is_available{$_} } keys %is_available ) {

If you want it efficient:

for my $p9 ( keys %is_available ) { next if ! $is_available( $p9 };

Which one of those is faster will probably depend on how many items get filtered out for looping. The grep is a loop in itself, so that solution actually loops twice with the second loop being "shorter"—depending on how many are filtered out. I expect grep to be a faster loop than the for, however, so that might still be a speed increase—depending on how many are filtered out.

All that's more or less irrelevant, however, until profiling your code shows that this is an issue. There's no need to make it faster until you're sure it's what's slowing you down.

Replies are listed 'Best First'.
Re^2: Foreach syntax
by chromatic (Archbishop) on Jul 26, 2008 at 05:35 UTC
    If you want it efficient...

    ... then use unless instead of the silly if !, as it's more efficient when parsing to only do one state machine transition instead of two.

    (Finally, an argument that the kind of people who think unless is EHORRIBLEAWFULEVILALWAYSANDFOREVER are likely to accept!)

      EHORRIBLEAWFULEVILALWAYSANDFOREVER

      Can we please have that error value reported by Parrot when it sees if ! ... or if not ... coded?

      And for any ludicrously large memory requests, how about EBYGUM?


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.