http://www.perlmonks.org?node_id=1013951


in reply to Two simple code style advice questions

I'd use 1b, in part because it is an important idiom. On a single line is even better. 1a is okay (the one advantage I'll grant it is that it avoids repeating either variable name -- I'm not sure why I've long used this only grudgingly). But if I wanted to go for maximum clarity, IMHO, I'd instead do:

my %ntests; $ntests{$_} = 0 for @tests;

Then there is:

@{ \my %ntests }{ @tests } = (0)x@tests; # :)

2a is pretty darn hackish and not something I'd expect to see in professional code. But I've come to find ternaries to often be less quick/easy to read than something like:

my $mol = ''; $mol = 'forty two' if 42 == $n;

Despite being 3 lines instead of 1, I find it significantly easier and faster to parse the intent. I especially don't like how the default value is almost lost in the single-line ternary. But I'd probably feel I was being a bit extravagant and then just use the 1-line ternary if the names and values are actually that short. For more and/or longer expressions, I'd format it more like:

my $mol = ! defined $n ? 'n/a' : 42 == $n ? 'forty two' : '';

(If I didn't use multiple "assignment \n\t if ...;" statements.)

- tye