1. Perl
  2. here

Conditional branching by if statement

When writing programming, you may want to change the process or repeat the same process depending on the conditions.

In such a case, conditional branch and repetition can be realized by using if and for statement.

Basics of conditional branch

I will explain the basics of conditional branch.

if statement

Use if statement to do conditional branch in Perl. First, let's write a simple conditional branch. This is an if statement that outputs "OK" when the value of the variable is "5".

my $num = 5;
if ($num == 5) {
  print "OK\n";
}

if statement has the following syntax. When the condition becomes true, the following blocks are executed.

if (condition) {
  ...;
}

= = is a comparison operator that returns true if the numbers are equal.

In the case of this example, "$num == 5" returns true because the variable contains 5.

And since the condition is true, the contents of the following blocks are executed.

Also check that "OK" is not displayed when you change the contents of the variable to "4".

if ~ else statement

By using if ~ else statement, you can write the process to be executed when the condition is true and the process to be executed when the condition is false.

# if statement
my $num = 5;
if ($num == 5) {
  print "OK\n";
}
else {
  print "Not OK\n";
}

if ~ elsif statement

You can use if ~ elsif statement to describe multiple conditions.

# if ~ elsif
my $num = 5;
if ($num == 5) {
  print "Number is 5\n";
}
elsif ($num == 7) {
  print "Number is 7\n";
}

In the above case, if "$num" is 5, "Number is 5" is displayed, and if "$num" is 7, "Number is 7" is displayed.

Note that in C and Java it is "else if", but in Perl it is "els if".

You can specify multiple elsifs.

# Multiple elsif
my $num = 5;
if ($num == 5) {
  print "Number is 5\n";
}
elsif ($num == 7) {
  print "Number is 7\n";
}
elsif ($num == 9) {
  print "Number is 9\n";
}

elsif can also be used in combination with else. Be sure to write else at the end.

# elseif and else combination
my $num = 5;
if ($num == 5) {
  print "Number is 5\n";
}
elsif ($num == 7) {
  print "Number is 7\n";
}
elsif ($num == 9) {
  print "Number is 9\n";
}
else {
  print "Not match\n";
}

Comparison operator

I used the symbol "==" in the condition of if statement, which is one of the comparison operators .

Here are the Perl comparison operators. Perl has two types of comparison operators. Numeric comparison operators and String comparison operators .

Numeric comparison operator

Numeric comparison operators are operators used to compare values as numbers.

*operator *meaning
A == B A and B are equal
A != B A and B are not equal
A> B A is greater than B
A >= B A is B or higher
A A is less than B
A <= B A is less than or equal to B

String comparison operator

The string comparison operator is an operator used to compare strings in lexicographical order.

*operator *meaning
A eq B A and B are equal
A ne B A and B are not equal
A gt B A is greater than B
A ge B A is B or higher
A lt B A is less than B
A le B A is less than or equal to B

Numerical comparison and string comparison

In Perl, use the numeric comparison operator if you want to compare values as numbers, and the string comparison operator if you want to compare as strings.

Please note that this is what makes it different from other languages.

# Numerical comparison
my $num = 4;
if ($num < 6) {
  ...
}

# String comparison
my $animal = 'Cat':
if ($animal eq 'Dog') {
  ...
}

String comparison operators include "gt", "ge", "lt", and "le" for comparing sizes, which are compared in lexicographical order.

For example, when comparing "1" and "03" numerically, "1" is interpreted as "1" and "03" is interpreted as "3", and "03" is larger.

However, when comparing the strings of "1" and "03", it is judged from the first character, and "1" and "0" are larger for "1" because the character code is larger for "1".

my $num1 = '1';
my $num2 = '03';

# Numerical comparison
if ($num1 > $num2) {
  # Not executed
  print "OK 1\n";
}

# String comparison
if ($num1 gt $num2) {
  # Be executed
  print "OK 2\n";
}

See below for a detailed explanation of Perl's comparison operators.

Perl boolean

Next, let's get a good understanding of Perl's boolean . In if statement, the inside of the block was executed when the condition became true. It was not executed when it became false.

Now let's get a good understanding of Perl booleans.

Perl false value

There are four false values in Perl:

1 undef Undefined value
2 "" Empty string
3 0 0
Four "0" String 0

If the condition of if statement is a false value as shown below, the inside of the block will not be executed.

# Not executed if condition is false
if (undef) {
  # Not executed
}

if ("") {
  # Not executed
}

if (0) {
  # Not executed
}

if ("0") {
  # Not executed
}

Perl true value

Everything is true except what is false above. For example, the following is true:

Long string

"Cat"

Non-zeroNumerical value

13
-3
1.5

A string containing a number other than "0"

"13"
"0.1"
"0.0"

Reference or object

my $nums = [1, 2, 3];
my $scores = {};
my $object = XML::Simple->new;

Notice that the string "" 0.0 "" is true.

list with elements

(0)
(1, 2);

If the condition of if statement is true as shown below, the inside of the block is executed.

# Executed if the condition is true
if ("Cat") {
  # Be executed
}

if (13) {
  # Be executed
}

if ("13") {
  # Be executed
}

my $object = XML::Simple->new;
if ($object) {
  # Be executed
}

When writing an array in the condition of an if statement

It's common to write an array in an if statement, so let's see how it is evaluated as a false value.

If the array has elements, it is evaluated in the scalar context and the number of arrays is evaluated.

If the array has elements, the if block will be executed, otherwise it will not be executed.

my @nums = (1, 2);
if (@nums) {
  # Be executed
}

my @nums = ();
if (@nums) {
  # Not executed
}

See below for more information on Perl booleans.

Perl logical operators

Next, I will explain the logical operators that can express "A and B", "A or B", and "not A".

So far, we've only looked at a single condition, but you can use logical operators to express complex conditions and negations.

*operator *meaning
| | Logical sum
&& Logical AND
!! denial
or OR (lower priority than &&)
and Lower priority than AND &&)
not Negation (lower priority than!)

Logical product (A and B)

For example, to express the condition that the variable "$num" is "greater than 1 and less than 5", use && and write as follows.

if ($num > 1 && $num < 5) {
  ...
}

And has the same meaning, but the priority of the operator is low, and it is customary to use "&&" when writing in the conditional part of if statement.

OR (A or B)

Next, to express the condition that the variable "$num" is "less than 1 or greater than 5", use || and write as follows.

if ($num < 1 || $num > 5) {
  ...
}

Or has the same meaning, but the priority of the operator is low, and it is customary to use "||" when writing in the conditional part of if statement.

Negation (not A)

To express the condition that the variable "$num" is "not true", we can use ! to write:

if (!$num)) {
  ...
}

Not has the same meaning, but the operator priority is low, and it seems that it is rarely used in the source code.

Use a combination of logical operators

Logical operators can be used in combination. You can control the join order of operators by using parentheses.

if ($num > 10 || (($num> -3 && $num < 6) &&! ($Num == 0))) {
  ...
}

The join order of "&&" is higher than the join order of "||", and some parentheses in the middle are not programmatically meaningful. Let's use "()" for.

Please refer to the following articles for a detailed explanation of logical operators.

Slightly special conditional branch

Learn about some of the more unusual conditionals that are often used in Perl.

unless statement

unless statement can write the same processing as when the condition is denied by if statement.

# Execute block if $num is not true
unless ($num) {
  ...
}

It has exactly the same meaning as the following if statement.

if (!$num) {
  ...
}

When should unless statement be used if the meanings are the same? That is when you want to strengthen your feelings of "otherwise". The feeling that unless is "otherwise" stands out.

For example, if the error checking process is the main process, writing the following is more noticeable than writing using "if" and "!". It is a process to execute a block when a value is not defined using define function.

unless (defined $num) {
  ...
}

Write the branch in the failed process with or

Perl often customarily writes conditional branch using logical operator or.

In a typical example, "or" will appear in the error handling when open function fails.

If the open function fails and returns a false value, the processing after the "or" is performed.

open(my $fh, "<", $file)
  or die "Can't open $file:$!";

The main processing is written first, and the auxiliary error processing is written later using or. One of the interesting things about Perl is that you can write programming in a natural language-like expression like this.

Postfix if and postfix unless

In Perl, if and unless can be written after the process.

# Postfix if
$num1 = 1 if !defined $num1;

# Postfix unless
$num2 = 1 unless defined $num2;

This is more accurately called if modifier and unless modifier.

If it is a conditional branch that can be written in one line, it can also be written using the postfix if and unless.

The biggest merit of postfix if and unless is that unlike normal if and unless, it does not create a scope, so processing is faster. Normally you don't need to be aware of it, but if you really want to gain speed, it will be a little faster.

I often use it with next statement and last statement.

for my $num (@nums) {
  last if !defined $num;
}

for my $num (@nums) {
  next if !defined $num;
}

Ternary operator

Perl has an operator called ternary operator.

You can use the ternary operator to change the value to be returned depending on the conditions.

# Ternary operator syntax
Condition? Value 1: Value 2

If the condition is true, the value 1 is returned, and if false, the value 2 is returned.

In the following example, "Cat" is assigned to "$animal" when "$flag" is true, and "Dog" is assigned to "$animal" when it is false.

my $flag = 1;

# Ternary operator
my $animal = $flag ? 'Cat':'Dog';

You can do the same with conditional branch using if, but you can write it concisely using the ternary operator.

Use multiple ternary operators

Multiple ternary operators can be used in layers, and can be written in a way that corresponds to "if ~ elsif ~ else".

my $flag = 2;

my $animal =
    $flag == 0 ? 'Cat'
  : $flag == 1 ? 'Dog'
  : $flag == 2 ? 'Mouse'
  :'Cow';

Since "$flag" is "2", "Mouse" is assigned to "$animal". When using ternary operators in layers, it is recommended to write them in multiple lines for easy viewing.

Set default values with special assignment operators "||=" and "//="

Perl has a commonly used default value setting method. It is a way to use special assignment operator "||=" or "//=" .

# If "$x" is false, set "$x" to 5.
$x ||= 5;

# Set 7 to "$y" if "$x" is undefined
$y //=7;

For "A ||= B", if "A" is false, the content of "B" is assigned to "A".

For "A //= B", if "A" is undefined, the contents of "B" will be assigned to "A".

The syntax for "A //= B" was introduced in Perl 5.10, so you can use "A //= B" in Perl 5.10 and later. "A ||= B" is prone to bugs, so it is recommended to use it. For example, if "A ||= B", the default value will be set when "A" is "0".

Remember this because it's a frequently used syntax.

Repeat statement

Please refer to the following article for repetitive sentences.

Related Informatrion