Home > Articles > Web Development > Perl

This chapter is from the book

The if Statement

To control whether statements are executed based on a condition in a Perl program, you usually use an if statement. The syntax of an if statement is as follows:

if (expression) block

The statement works like this: If the expression evaluates to true, the block of code is run. If the expression is false, the block of code is not run. Remember that the block includes the braces. Consider this example:

if ( $r == 5 ) {
  print ‘The value of $r is equal to 5.’;
}

The expression being tested is $r == 5. The == symbol is an equality operator. If the two operands on either side—$r and 5—are numerically equal to one another, the expression is considered to be true, and the print statement is executed. If $r is not equal to 5, the print statement is not executed.

The if statement can also run one set of statements if a condition is true and another set of statements if it’s not. That structure is called an if-else statement. The syntax looks like this:

if (expression)   #If expression is true...
  block1      # ...this block of code is run.
else
  block2      # Otherwise this block is run.

The first block, block1, is run only if the expression is true; if the expression is not true, block2, following the else, is run. Now consider this example:

$r=<STDIN>; 
chomp $r;
if ($r == 10) {
  print ‘$r is 10’, "\n";
} else {
  print ‘$r is something other than 10...’, "\n";
  $r=10;
  print ‘$r has been set to 10’, "\n";
}

Yet another way of structuring an if statement is to check multiple expressions and run code depending on which expressions are true:

if (expression1)   # If expression1 is true ...
  block1      # ...run this block of code.
elsif (expression2) # Otherwise, if expression2 is true...
  block2      # ...Run this block of code.
else
  block3      # If neither expression was true, run this.

You can read the preceding block like this: If the expression labeled expression1 is true, the block block1 is run. Otherwise, control falls to the elsif and expression2 is tested; if it’s true, block2 is run. If neither expression1 nor expression2 is true, block3 is run. The following is an example of real Perl code that demonstrates this syntax:

$r=10;
if ($r==10) {
  print ‘$r is 10!’;
} elsif ($r == 20) {
  print ‘$r is 20!’;
} else {
  print ‘$r is neither 10 nor 20’;
}

The Other Relational Operators

So far, you’ve been comparing numeric quantities in your if statements with the equality operator, ==. Perl actually has quite a few operators for comparing numeric values, most of which are listed in Table 3.1.

Table 3.1 Numeric Relational Operators

Operator

Example

Explanation

==

$x == $y

True if $x equals $y

>

$x > $y

True if $x is greater than $y

<

$x < $y

True if $x is less than $y

>=

$x >= $y

True if $x is greater than or equal to $y

<=

$x <= $y

True if $x is less than or equal to $y

!=

$x != $y

True if $x is not equal to $y


To use these operators, you can simply put them in anywhere that your program needs to test relations between numeric values. An example of the use of these operators in an if statement is shown in Listing 3.1, which you can type in and run (do not type the line numbers—"1:" and so forth). The various parts of the program work as follows:

Listing 3.1 A Small Number Guessing Game

1:  #!/usr/bin/perl -w
2:
3:  $im_thinking_of=int(rand 10);
4:  print "Pick a number:";
5:  $guess=<STDIN>;
6:  chomp $guess;  # Don’t forget to remove the newline!
7:
8:  if ($guess>$im_thinking_of) {
9:    print "You guessed too high!\n";
10: } elsif ($guess < $im_thinking_of) {
11:   print "You guessed too low!\n";
12: } else {
13:   print "You got it right!\n";
14: }
  • Line 1: This line is the standard first line of a Perl program; it indicates the interpreter you want to run and the -w switch to enable warnings. See Hour 1, "Getting Started with Perl"; your first line may need to look slightly different.

  • Line 3: The (rand 10) function picks a number between 0 and 10, and the int()function truncates it so that only integers 0 to 9 are assigned to $im_thinking_of.

  • Lines 4–6: These lines ask the user for the guess, assign it to $guess, and remove the trailing newline character.

  • Lines 8–9: If $guess is greater than the number in $im_thinking_of, these lines print an appropriate message.

  • Lines 10–11: Otherwise, if $guess is less than the number in $im_thinking_of, these lines print that message.

  • Lines 12–13: The only choice left is that the user guessed the number.

The operators in Table 3.1 are used only for testing numeric values. Using them to test nonalphabetic data results in behavior that you probably don’t want. Consider this example:

$first="Simon";
$last="simple";
if ($first == $last) {  # == is not what you want!
  print "The words are the same!\n"; 
}

The two values $first and $last actually test equal to each other. The reason was explained in Hour 2: If nonnumeric strings are used when Perl is expecting numeric values, the strings evaluate to zero. So the preceding if expression looks something like this to Perl: if ( 0 == 0 ). This expression evaluates to true, and that’s probably not what you wanted.

If you want to test nonnumeric values, you can use another set of Perl operators, which are listed in Table 3.2.

Table 3.2 Alphanumeric Relational Operators

Operator

Example

Explanation

eq

$s eq $t

True if $s is equal to $t

gt

$s gt $t

True if $s is greater than $t

lt

$s lt $t

True if $s is less than $t

ge

$s ge $t

True if $s is greater than or equal to $t

le

$s le $t

True if $s is less than or equal to $t

ne

$s ne $t

True if $s is not equal to $t


These operators decide "greater than" and "less than" by examining each character left to right and comparing them in ASCII order. This means that strings sort in ascending order: most punctuation first, and then numbers, uppercase, and finally lowercase. For example, 1506 compares less than Happy, which compares less than happy.

What Truth Means to Perl

Up to this point, you’ve been reading about "if this expression is true..." or "...evaluates to true...," but you haven’t seen any formal definition of what Perl thinks "true" is. Perl has a few short rules about what is true and what is not true, and the rules actually make sense when you think about them for a bit. The rules are as follows:

  • The number 0 is false.

  • The empty string ("") and the string "0" are false.

  • The undefined value undef is false.

  • Everything else is true.

Make sense? The only other point to remember is that when you’re testing an expression to see whether it’s true or false, the expression is simplified—functions are called, operators are applied, math expressions are reduced, and so on—and then converted to a scalar value for evaluation to determine whether it is true or false.

Think about these rules, and then take a look at Table 3.3. Try to guess whether the expression is true or false before you look at the answer.

Table 3.3 True or False Examples

Expression

True or False?

0

False. The number 0 is false.

10

True. It is a nonzero number and therefore true.

9>8

True. Relational operators return true or false, as you would expect.

-5+5

False. This expression is evaluated and reduced to 0, and 0 is false.

0.00

False. This number is another representation of 0, as are 0x0, 00, 0b0, and 0e00.

""

False. This expression is explicitly mentioned in the rules as false.

" "

True. There’s a space between the quotes, which means they’re not entirely empty.

"0.00"

True. Surprise! It’s already a string, but not "0" or "". Therefore, it is true.

"00"

True also, for the same reason as "0.00"

"0.00" + 0

False. In this expression, 0.00+0 is evaluated, the result is 0, and that is false.


Until now, you’ve seen only expressions with relational operators as the conditions in if statements. Actually, you can use any expression that will evaluate to true or false the way you would want:

# The scalar variable $a is evaluated for true/false
if ($a) { ... }

# Checks the length of $b. If nonzero, the test is true.
if (length($b)) { .... }

Recall from Hour 2 that the assignment operator = returns a value—the value that was assigned. That value, of course, is also true or false:

$a = 1;
$b = 2;
print qq(The statement "$a = $b" is );
if ($a = $b) { # value is 2, therefore true
  print "true";
} else {
  print "false";
}

This code prints The statement "1 = 2" is true. Now you see why using = when you meant == is such a pitfall.

The value undef is a special value in Perl. Variables that have not yet been set have the value of undef, and some functions return undef on failure. It’s not 0, and it’s not a regular scalar value. It’s kind of special. In a test for truth, undef always evaluates to false. If you try to use the undef value in a math expression, it’s treated as though it were 0.

Using variables that haven’t been set yet is usually a sign of a programming error. If you’re running your Perl programs with warnings enabled, the value undef in an expression or as an argument to some functions causes Perl to generate the warning Use of uninitialized value.

Logical Operators

When you’re writing programs, you sometimes need to code something like the following: Do this if $x is true and if $y is true, but not if $z is true. You can code this example into a series of if statements, but it’s not pretty:

if ($x) {
  if ($y) {
    if ($z) {
      # do nothing
    } else {
      print "All conditions met.\n";
    }
  }
}

Perl has a whole class of operators for connecting together true and false statements like this, called logical operators. The logical operators are shown in Table 3.4.

Table 3.4 Logical Operators

Operator

Alternative Name

Example

Analysis

&&

and

$s && $t

True only if $s and $t are true

 

 

$q and $p

True only if $q and $p are true

||

or

$a || $b

True if $a is true or $b is true

 

 

$c or $d

True if $c is true or $d is true

!

not

! $m

True if $m is not true

 

 

not $m

True if $m is not true


Using the operators in Table 3.4, you could rewrite the previous snippet much more concisely as follows:

if ($x and $y and not $z ) {
  print "All conditions met.\n";
}

Expressions connected with logical operators are evaluated from left to right, until a value of true or false can be determined for the entire expression. Examine the following code:

1:  $a=0;
2:  $b=1;
3:  $c=2;
4:  $d="";
5: if ($a and $b) { print ‘$a and $b are true’; }
6: if ($d or $b) { print ‘either $d or $b is true’; }
7: if ($d or not $b or $c) 
8:   { print ‘$d is true, or $b is false or $c is true’; }
  • Lines 1–4: These lines give the variables default values.

  • Line 5: $a is evaluated first. It is false, so the and expression cannot possibly be true. $b is never evaluated; it doesn’t have to be because the truth of the expression is known after evaluating $a. The print is not executed.

  • Line 6: $d is evaluated first. It is false. Even if $d is false, the expression might still be true—because it contains a logical or—so $b is examined next. $b turns out to be true; therefore, the expression is true, and the print happens.

  • Line 7: $d is evaluated first. It is false. But although $d is false, the expression might still be true—as seen in line 4—because it contains a logical or. Next, the truth of $b—1, so true—is negated, so this expression becomes false. The truth of the or statement cannot be determined yet, so $c is evaluated. $c turns out to be true, so the whole expression is true, and the print happens.

This behavior—stopping the evaluation of a logical expression as soon as the truth can be determined—is called short-circuiting. This feature is used by Perl programmers to construct simple flow-control statements out of logical operators and to avoid the if statement entirely:

$message="A and B are both true."
($a and $b) or $message="A and B are not both true.";

In the preceding example, if either $a or $b is false, the right side of the or must be evaluated, and the message is changed. If both $a and $b are true, the or must be true, and it’s not necessary to evaluate the right side. The truth value of the entire expression isn’t used at all; this example uses the short-circuit side effects of the and and or operators to manipulate $message.

An interesting property of Perl’s logical operators is that they don’t simply return true or false. They actually return the last value evaluated. For example, the expression 5 && 7 doesn’t just return true—it returns 7. This allows constructs like this:

# Set $new to old value if $old is true, 
# otherwise use the string "default".
$new=$old || "default"; 

which is a little more concise than the code

$new=$old;
if (! $old) { # was $old empty (or false)?
  $new="default";
}

This trick can make your code less readable. Understanding how it works can be helpful, though, if you are going to be looking at much Perl code written by others.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020