in reply to order of arguments evaluated

I recently implemented the following code.. I THINK I'm safe but I'm not 100% sure.. I would tend to shy away from such code..

my $rownew = 0; foreach my $box ( @boxes ) { if ( $rownew ? 1 : $rownew++ ) { print( "," ); } print( $box ); }

This, too, depends on the fact that $rownew is evaluated on the left hand side of the ? operator before the result. It's one of the few times, if ever, that I would want to be silly enough to mix ++ and dependant code on the one line.

Replies are listed 'Best First'.
Re^2: order of arguments evaluated
by Roy Johnson (Monsignor) on May 31, 2005 at 18:25 UTC
    That could be better written as
    print join ',', @boxes;
    unless you're concerned about the joined string being enormous, in which case I'd probably say
    my $printed = 0; foreach my $box ( @boxes ) { print ',' if $printed++; print $box; }
    But your code is perfectly safe. The alternatives are only evaluated if the corresponding condition indicates that they should be.

    Caution: Contents may have been coded under pressure.
      Indeed both are good suggestions, but the context was putting together HTML tables, hence a simple join wasn't satisfactory.

      The second solution was also good, but I was concerned about integer wrap-around, which could potentially evaluate to zero in the case of a HUGE table (being the paranoid programmer that I am, even though the likelihood of generating a 4,294,967,296 row table was unlikely).

      Hence the dodgy trinary operator statement.

        My second solution, like yours, will only increment the variable if it is zero, because logical-or is a short-circuiting operation.

        Before you get done generating a multi-billion-row table, I think you're going to have problems with browser timeout. :-)


        Caution: Contents may have been coded under pressure.