Possible ways:
-
Using push:
my @list; push @list, 'foo' if $foo; push @list, 'bar' if $bar; -
Using the conditional operator:
my @list = ( $foo ? 'foo' : (), $bar ? 'bar' : (), ); -
Using the
x!!Boolean list squash operator:my @list = ( ('foo') x!! $foo, ('bar') x!! $bar, );
Which one is better and why?
Well, they all do different things.
However, all other factors being equal,
is the statement that conveys its meaning most directly, so it should be preferred.
If you have to pause and think about statement that supposedly does something as simple as pushing an array element, you are doing something wrong.
could be OK if this is part of some colossal initialization that is being done elsewhere.
I think using
indicates that the programmer has —how can I put this?— issues.
Incidentally, there is no such thing called the
x!!composite operator. The!!is double logical negation. It converts an arbitrary false value to a defined but false value (the empty string) which yields0when used whereperlexpects a number. A true value is converted to a1. Here,!!operates on$fooand$barand writing itx!! $foounnecessarily obfuscates the meaning of the code.xis the repetition operator. So,means repeat
('foo')once or not at all, depending on whether$foois true or false, respectively.PS: Of course, it turns out there was a PerlMonks article introducing the so-called boolean list squash operator. I read the article and find it unconvincing.