in reply to Re: Loop once on condition 1, many times on cond. 2?
in thread Loop once on condition 1, many times on cond. 2?

That's certainly much tidier notation.

The problem with mine is that it loops through all keys no matter what- it just doesn't execute the block of code when not necessary. What I was hoping for is a formula that only loops once when one loop is all that's needed. But I think your tidy notation functions the same as mine, no?




Time flies like an arrow. Fruit flies like a banana.
  • Comment on Re^2: Loop once on condition 1, many times on cond. 2?

Replies are listed 'Best First'.
Re^3: Loop once on condition 1, many times on cond. 2?
by ikegami (Patriarch) on Oct 09, 2008 at 15:32 UTC
    No.

    The expression is evaluated before the loop starts in order to build the list of items over which to iterate,
    and the expression returns either the result of keys or a single scalar depending on whether conditional's condition is true,
    so it either loops for every key or just once.

Re^3: Loop once on condition 1, many times on cond. 2?
by jethro (Monsignor) on Oct 09, 2008 at 15:33 UTC

    No, because the ?: delivers either a list consisting of the single value or all the keys to the 'foreach' loop statement . So if that is only one value, the loop executes only for that single value.

      Excellent, thanks.

      I'll read up on this notation.




      Time flies like an arrow. Fruit flies like a banana.
        Some maintainability may be gained at the cost of some concision by separating out loop list generation:
        my @keys_to_process = $x eq 'key_1' ? keys %my_hash : exists $my_hash{$x} ? ($x) : () # default - nothing to do ; foreach $key (@keys_to_process) { do_something_with($key); }
        Further, because the above will loop over all keys if $x eq 'key_1' is true even if 'key_1' does not exist in the hash (which may or may not be what you want: Your Logic May Vary), perhaps re-order list generation:
        my @keys_to_process = ! exists $my_hash{$x} ? () : $x eq 'key_1' ? keys %my_hash : ($x) ;

        You can chain these suckers... so to ensure you do nothing if $x doesn't appear in %my_hash:

        foreach $key ( ($x eq 'key_1') ? keys %my_hash : exists $my_hash($x) +? $x : () ) { do a bunch of stuff }
        noting that if $x does not exist, what you want is an empty list.