Site Menu
LINUX CLASSES - PERL PROGRAMMING

Is Perl Logical?

A Perl script that's just a sequence of commands executed one after the other isn't very exciting. Let's look at how to use if/then/else logic and looping constructs to control the flow of a Perl program. Conditional Operations

The general form of an if-then-else construct is shown here, with the actual syntax shown in boldface and the parts you must supply in normal type:

if ( condition is true ) {
execute these commands
}
else {

execute those commands
}

The else clause is optional, but you can also have nested if clauses by using the elsif construct like this:

if ( condition is true ) { execute these commands }
elsif {
execute those commands }
elsif {
execute those commands }
else {
execute those commands }

So what kind of conditions can we test for? For number and string comparisons, here are the conditional expressions you can use. In other words, any of these expressions can go inside the parentheses of the if or elsif statement:

Numbers Strings Result

$a == $b $a eq $b True if $a is equal to $b.

$a != $b $a ne $b True if $a is not equal to $b.

$a > $b $a gt $b True if $a is greater than $b.

$a < $b $a lt $b True if $a is less than $b.

$a >= $b $a ge $b True if $a is greater than or equal to $b.

$a <= $b $a le $b True if $a is less than or equal to $b.

Using the wrong comparison operator is a common Perl coding error, and is frustrating to debug. For example, if you use the == operator to compare two strings, you will not get the expected result.

You can also test certain file conditions, such as whether or not files exist, the type of file, and so on. Here are the conditional expressions for files:

Conditional Expression Result

-e $somefile True if somefile exists.

-f $somefile True if somefile exists and is a plain file.

-d $somefile True if somefile exists and is a directory.

-s $somefile True if somefile contains data (the size is not zero).

-r $somefile True if somefile is readable.

-w $somefile True if somefile is writable.

-x $somefile True if somefile is executable.

And finally, here are the logical operators, for performing tests that involve and, or, and not conditions:

Operator Result

$a && $b True if both $a< EM> and $b are true.

$a and $b Same as above.< /P>

$a || $b True if either $a or $bi s true.

$a or $b Same as above.< /P>

! $a True if $a is false.

not $a Same as above.

Some if/then/else Examples

Here are some examples using the conditional expressions just listed. Note that the spaces on either side of the parentheses and braces are optional, and the placement of them is largely a matter of style.

if ( $carprice > 20000 )
{
print 'Too rich for my blood.';
}
else
{
print
'Can you get that model in blue?'; }

if (
$maker eq "Buick"
)
{
print 'Have you driven a Ford lately?';
}

if (
-r $myfile && -s $myfile
)
{

print "The $myfile file is readable and contains data."

}

The case Statement

Most languages provide a case or switch statement that lets you compare a string with several possible values and execute a block of code when a match is found. Perl does not, but it does provide a way to implement this procedure. Here's an example of the SWITCH construct, with the syntax shown in boldface and the parts you would supply in normal type:

SWITCH: {
if (
$A eq "ls"
) { system("ls"); last SWITCH };
if (
$A eq "pwd"
) { system("pwd"); last SWITCH };
if (
$A eq "date"
) { system("date"); last SWITCH };
print "None of the args were very interesting. \n";

}

In this example, if the value of $A was ls, the first block of commands would execute. If the value of $A was pwd, the second block of commands would execute. Otherwise, the rest of the commands in the SWITCH clause would execute. The last SWITCH command tells Perl to short-circuit the rest of the stuff in the SWITCH clause, so as soon as one of the conditions is satisfied, the others are ignored.

Previous Lesson: Perl Arguments
Next Lesson: Perl Looping

[ RETURN TO INDEX ]


   

Comments - most recent first
(Please feel free to answer questions posted by others!)

Bob Rankin     (24 Aug 2011, 20:54)
@Vickie, thanks for the thought provoking content. But I wonder if this isn't a semantic (no pun intended) argument? Couldn't one write the elsif as "else if" and thereby see the nesting clearly? For example:

if (recipe == "delicious meringue") { make pie; }
else
if (recipe = "deadly ricin") { leave kitchen immediately; }
else
if ( (research == "thesis") && (topic = "thermonuclear device")) { police content; }
else { inform the public; }

If you replaced the "elsif" with a plain "if" then I agree it would be linear, and it would be possible for more than one of the if's to be satisfied. With "elsif" or "else if" only one of the conditions could be satisfied.
Vickie     (24 Aug 2011, 19:34)
Hi Dr. Bob,

Enjoying your material and thank you for it.

The following... "The else clause is optional, but you can also have nested if clauses by using the elsif construct like this:

if ( condition is true ) { execute these commands }
elsif { execute those commands }
elsif { execute those commands }"

...is not an example of nested if statements, but rather linear. elsif keeps the nesting at the same level as the outer block. Plain old if statements would be nested.

vjg
spike     (09 Nov 2010, 04:00)
Perl now has a switch statement implemented via a module:

use Switch;
Bob Rankin     (10 May 2010, 21:17)
Fixed now, thanks!
ND Stegs     (10 May 2010, 15:06)
Minor editing: you have two "greater than" lines. The second should be the "less than" line.
Russell     (21 Jan 2010, 09:22)
Awesome guide! I check here often when I forget the syntax for various Linux commands or programming tasks. Thanks for making this available.

I welcome your comments. However... I am puzzled by many people who say "Please send me the Linux tutorial." This website *is* your Linux Tutorial! Read everything here, learn all you can, ask questions if you like. But don't ask me to send what you already have. :-)

NO SPAM! If you post garbage, it will be deleted, and you will be banned.
*Name:
Email:
Notify me about new comments on this page
Hide my email
*Text:
 
 


Ask Bob Rankin - Free Tech Support


Copyright by - Privacy Policy
All rights reserved - Redistribution is allowed only with permission.