How to use if, else statements in a Perl

Home > Search > How-to
  by

Equals

An if statement that includes then and else can be used to do something if a condition is either true or false. In this example, "Foo does equal 1" will display if foo equals 1, and "Foo does not equal 1" will display if foo does not equal 1.

print "Enter a number.\n";
my $number = <STDIN>;
if ($number == 10) {
    print "Your number is greater than or equal to 10.\n";
} else {
    print "Your number is less than 10.\n";
}

 


Greater than, Less than

An if statement that includes then and else can be used to do something if a condition is either true or false. In this example, "Foo does equal 1" will display if foo equals 1, and "Foo does not equal 1" will display if foo does not equal 1.

print "Enter a number.\n";
my $number = <STDIN>;
if ($number >= 10) {
    print "Your number is greater than or equal to 10.\n";
} else {
    print "Your number is less than 10.\n";
}

If exists

The -e option can be used to determine if a file or directory exists.

if (-e "/path/to/file.txt") {
    print "File.txt exists.\n";
} else {
    print "File.txt does not exist.\n";
}

 


String contains

print "Enter some text.\n";
my $text = <STDIN>;
if ($text =~ /Hello/) {
    print "Your text contains the word Hello.\n";
} else {
    print "Your text does not contain the word Hello.\n";
}

 


String begins with

print "Enter some text.\n";
my $text = <STDIN>;
if ($text =~ /^Hello/) {
    print "Your text begins with the word Hello.\n";
} else {
    print "Your text does not begin with the word Hello.\n";
}

 


String does not begins with

print "Enter some text.\n";
my $text = <STDIN>;
if ($text !~ /^Hello/) {  
    print "Your text does not begin with the word Hello.\n";
} else {
    print "Your text begins with the word Hello.\n";  
}

 


If variable does not equal

print "Enter some text.\n";
my $text = <STDIN>;
if ($text !~ /Hello|World/) {  
    print "You did not enter Hello or World.\n";
} else {
    print "You entered Hello or World.\n";  
}

 


Multiple conditions

print "Enter some text.\n";
my $text = <STDIN>;
if (($text ne /^Hello/ and $text ne /$World/) or ($text ne /^Greetings/ and $text ne /$Earth/)) {  
    print "Your text does not begin with the word Hello and does not end with World or does not being with Getttings and does not end with Earth.\n";
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments