How to use if, else statements in a Perl

Home > Search > How-to

Equal, 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";


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";


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.