Jun 21

Shorthand if-clause

Category: Linux,Perl   — Published by tengo on June 21, 2008 at 7:10 am

There is a handy short version for a classic if-else-statement that is very useful, but everytime I'd like to use it, I just can't fully remember what its syntax was. And looking it up on google is hard, because "if" is a very common word... It is especially useful on initializing variables in a cgi environment, where the start value of a $var depends on a passed form value.

So here it is. Instead of writing:

form->{var} = undef;
my $var;
if($form->{var}){
$var = $form->{var};
}else{
$var = 1;
}

use this elegant shorthand if-clause:

my $var = $form->{var} ? $form->{var} : 1;

which is short for: if $form->{var} is true ($form->{var} set), use it, else default to 1

Another shorthand variable declaration

The above is useful if you need to declare a variable and three variables are involved. If you just need to test if a passed variable holds a value/is true, another construct might be useful:

$var = $form->{var} || 1;

which is short for: if $form->{var} holds a (true) value, use it, else default to 1