O'Reilly logo

Beginning Perl for Bioinformatics by James Tisdall

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Conditionals and Logical Operators

This section covers conditional statements and logical operators.

true and false

In a conditional test, an expression evaluates to true or false, and based on the result, a statement or block may or may not be executed.

A scalar value can be true or false in a conditional. A string is false if it's the empty string (represented as "" or ''). A string is true if it's not the empty string.

Similarly, an array or a hash is false if empty, and true if nonempty.

A number is false if it's 0; a number is true if it's not 0.

Most things you evaluate in Perl return some value (such as a number from an arithmetic expression or an array returned from a subroutine), so you can use most things in Perl in conditional tests. Sometimes you may get an undefined value, for instance if you try to add a number to a variable that has not been assigned a value. Then things might fail to work as expected. For instance:

use strict;
use warnings;
my $a;
my $b;
$b = $a + 2;

produces the warning output:

Use of uninitialized value in addition (+) at - line 5.

You can test for defined and undefined values with the Perl function defined .

Logical Operators

There are four logical operators:

not
and
or
xor

not turns true values into false and false values into true. Its use is best illustrated in code:

if(not $done) {...}

This executes the code only if $done is false.

and is a binary operator that returns true if both its operands are true. If one or both of the operands are false ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required