in reply to Re: foreach loop - could it beeeeee!!
in thread foreach loop - could it beeeeee!!

Surely ‘should’ (instead of ‘could’) is a bit strong? “Your code isn't as brief as it could be” is quite different from “Your code must be changed”; and, especially for folks like me who can never remember precedence, it's easy on a quick read to bracket as
(my $pick = $choice_array[0]) eq ('correct' ? 'aaa' : 'bbb')
, which makes the whole very confusing. There's not even any potential for repeated side effects with the original code—it's just a tiny bit of repeated typing.

Replies are listed 'Best First'.
Re^3: foreach loop - could it beeeeee!!
by bart (Canon) on Oct 11, 2009 at 12:56 UTC
    If you're going to start arguments about "readability for newbies", then I'll chip in and simply state that a "?:" syntax construct should not be used for statements (in void context), but only for expressions. For statements you should be using if/else instead.
    my $pick; if($choice_array[0]) eq 'correct') { $pick = 'aaa'; } else { pick = 'b +bb'; }

    All IMHO, of course.

    Finally, I must say that I think that all this "readability for newbies" is all a pile of nonsense. Just make it readable for yourself.

      I must say that I think that all this "readability for newbies" is all a pile of nonsense. Just make it readable for yourself.
      For the record, what I said was “… for folks like me who can never remember precedence …”. I am no expert, to be sure, but I'm not entirely a newbie, either. :-)
        Well, the don't take it personally, then...

        I always find that these arguments about readability degenerate into an argument for readability for a hypothetical user. Usually this user is a newbie who, apparently, is clueless about Perl idioms. So the more more the code looks like other languages, such as Java, the better.

        Well, I don't buy it. The main reason why people use Perl instead of any other language, is because it makes it easier to do certain tasks than those other languages. Restricting yourself to a subset so those people coming from other languages can read it, is simply throwing away that advantage.

        So, let's say I was just one step ahead of you, then... :)

Re^3: foreach loop - could it beeeeee!!
by ikegami (Patriarch) on Oct 11, 2009 at 18:04 UTC

    Surely ‘should’ (instead of ‘could’) is a bit strong?

    I don't think so. Anything but the trivial use of the conditional operator is usually unreadable. The OP's code is definitely unreadable. Part of the reason his code is unreadable is due to his non-standard and verbose use of the conditional operator.

    it's easy on a quick read to bracket a

    I usually add parens around the conditional operator for similar reasons:

    my $pick = ( $choice_array[0] eq 'correct' ? aaa : bbb );
    my $pick = ( $choice_array[0] eq 'correct' ? aaaaaaaaaaaaaaaaaaaaaaaaaaa : bbbbbbbbbbbbbbbbbbbbbbbbbbb );