Categories
Perl

Perl Shorthand If Clause

Perl has a ton of short hand features. One that a lot of non-beginners use, and that I forget frequently, is the perl short hand if clause. This tutorial will show you how to use the shorthand if clause in perl:

Perl has a ton of short hand features. One that a lot of non-beginners use, and that I forget frequently, is the perl short hand if clause. This tutorial will show you how to use the shorthand if clause in perl:

Perl “IF” Clause, Normally…

Typically if you want to do an if statement in perl, you would do something like this:


my $data;
if($form->{somefield}){
  $data = $form->{somefield};
}else{
  $data = 1;
}
print $data;

Perl Shorthand “IF” Clause

But, if you wanted to do the shorthand version of the if statement, here is how you would code it:


my $data = $form->{somefield} ? $form->{somefield} : 1;
print $data;

Another Example of Using the Shorthand Perl IF Clause:


print $form->{somefield} ? $form->{somefield} : 1;

Both examples will either use the data that is in the $hash{value} container, or it will use the number 1 if the hash{value} is empty.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.