Skip to Main Content
Learning Perl, 5th Edition
book

Learning Perl, 5th Edition

by Randal L. Schwartz, Tom Phoenix, brian d foy
June 2008
Beginner content levelBeginner
352 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from Learning Perl, 5th Edition

The if Control Structure

Once you can compare two values, you’ll probably want your program to make decisions based upon that comparison. Like all similar languages, Perl has an if control structure:

if ($name gt 'fred') {
  print "'$name' comes after 'fred' in sorted order.\n";
}

If you need an alternative choice, the else keyword provides that as well:

if ($name gt 'fred') {
  print "'$name' comes after 'fred' in sorted order.\n";
} else {
  print "'$name' does not come after 'fred'.\n";
  print "Maybe it's the same string, in fact.\n";
}

Those block curly braces are required around the conditional code (unlike C, whether you know C or not). It’s a good idea to indent the contents of the blocks of code as we show here; that makes it easier to see what’s going on. If you’re using a programmers’ text editor (as discussed in Chapter 1), it’ll do most of the work for you.

Boolean Values

You may actually use any scalar value as the conditional of the if control structure. That’s handy if you want to store a true or false value into a variable, like this:

$is_bigger = $name gt 'fred';
if ($is_bigger) { ... }

But how does Perl decide whether a given value is true or false? Perl doesn’t have a separate Boolean data type, like some languages have. Instead, it uses a few simple rules:[*]

  • If the value is a number, 0 means false; all other numbers mean true.

  • Otherwise, if the value is a string, the empty string ('') means false; all other strings mean true.

  • Otherwise (that is, if the value is another kind of ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Perl, 6th Edition

Learning Perl, 6th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Beginning Perl

Beginning Perl

Curtis Ovid Poe
Learning Perl 6

Learning Perl 6

brian d foy
Mastering Perl

Mastering Perl

brian d foy

Publisher Resources

ISBN: 9780596520106Supplemental ContentErrata Page