Linux Classes
Linux Classes
Share This With a Friend
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 loopingconstructs 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 elsifstatement:

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 fileconditions, 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 && $bTrue if both $a< EM> and$bare true.

$a and $bSame as above.< /P>

$a || $bTrue if either $a or $bi s true.

$a or $bSame as above.< /P>

! $aTrue if $a is false.

not $aSame 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:




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

Popular Linux Topics

Linux Intro
Linux Files
Linux Commands
Change Password
Copy Files
Linux Shell Basics

Linux Tutorial

Who is Doctor Bob?
What is Linux?
History of Unix
Operating Systems
What's Next?

Linux Basics

Living in a Shell
Root and Other Users
Virtual Consoles
Logoff and Shutdown
Choosing a Shell
The Command Prompt
Wildcards
Command History
Aliases
Redirection
Pipelines
Processes
Stopping a Program
Environment Variables
Help!

Linux Files

The Linux File System
Linux File Names
Linux Directories
Directory Terminology
Navigating the File System
Listing Linux Files
Displaying Linux Files
Copying and Renaming Files
Creating Files and Directories
Deleting Files and Directories
Linux Files - Wildcards
The Nine Deadly Keystrokes
Linux File Permissions
Changing File Permissions

Linux Commands

Important Linux Commands
Changing Your Password
Switching Users
Who is Logged In?
Date and Time
The Echo Command
Spell Checking
Printing Linux Files
Joining Files
Searching for Files
Comparing Files
Task Scheduling
Linking Files

Linux Editors

The Vi Editor
The Emacs Editor
The Pico Editor

Linux Data Manipulation

Slicing & Dicing
Heads or Tails?
Sorting Data
Eliminating Duplicates
Selecting Columns
Selecting Records
Search & Replace
Crunching Data
Finding Files
Pipe Fitting

Linux Shell Programming

Linux Shell Scripts
Executing a Script
Shell Script Variables
Shell Script Logic
Shell Script Looping
Shell Script Debugging

Perl Programming

Perl Basics
Perl Variables
Perl Arguments
Perl Logic
Perl Looping
Perl and Files
Perl Pattern Matching

Linux and Email

Sending Email
Reading Email
Other Mail Commands
Using Pine for Email
The Pine Inbox
Pine Email Basics
Pine Email Folders
Pine for Power Users

Compression and Encoding

Linux File Compression
Archiving With Tar
Compression With Gzip
Compress and Zcat
Zmore and Zless
Zip and Unzip
Encoding and Decoding
Encryption

Linux Does DOS

Accesing DOS Files
Accesing DOS Partitions
Running DOS Programs

Managing Linux

Updating Your Linux System
Installing Packages with RPM
Uninstalling Packages w/ RPM
Upgrading Packages with RPM
Querying Packages with RPM

AltStyle によって変換されたページ (->オリジナル) /