I’ve used Perl for about 6 years now and I’m still running across new tricks that make my code more concise. Here’s one I just recently discovered:
It’s well known that you can use the “or” operator (that is, the literal word “or”) to take actions such as “die” if a command fails or returns a “false” or undefined value. Well, you can use the “||” (logical “or”) operator to give an assignment a default value (presumably the return value of the evaluated code fragment). For example, we can define variables in the following way:
my $var = $var1 || $var2;
In C++, this would return a boolean value. In Perl, it’s going to evaluate $var1 and either assign that value if it’s a “true” value or assign the value of $var2 if it isn’t. This is handy, because otherwise we’d be writing it my $var = ($var1) ? $var1 : $var2;, which is just klutzy and harder to read, to boot.
Note that using this as a boolean value still works: if $var1 is a true value, $var will also be the same true value. If $var1 is false and $var2 is true, $var will be the (true) value of $var2. If both are false, $var is going to also have a false value (probably undef, perhaps the value of $var2; the result is the same either way). This corresponds to the truth table for “or”:
V1 | V2 | V1 || V2 |
---|---|---|
T | T | T |
T | F | T |
F | T | T |
F | F | F |