1. Perl
  2. Syntax
  3. here

if modifier - postfix if

Perl has if modifier syntax. You can place if keyword after a statement.


This is an example using the if modifier. If the line starts with "#"(regular expression /^#/), The program jumps to the next loop.

for my $line (@lines) {
  next if $line =~ /^#/;

The benefits to use the if modifier is that a simple condition branch is written in one line. The combination with next are often used.

if statement creates scope, while the if modifier does not. Therefore, the if modifier has a little better performance.

unless modifier

The unless modifier also exists.

$num1 = 1 unless defined $num1;

The unless modifier is explained in detail below.

Example code

This is an example of if modifiers.

use strict;
use warnings;

# if modifier
print "1-2: Example of if modifier (next if)\n";
my @lines = (
  'The first line',
  '2nd line'

for my $line (@lines) {
  # If starts with # , go to the next line
  next if $line =~ /^#/;
  print $line, "\n";
print "\n";


1-2: Example of if modifier (next if)
The first line
2nd line

Related Informatrion