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"; } Unlike in C, those block curly braces are required around the conditional code. 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.
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:
1. The special value undef is false. (We'll see this a little later in this section.)
2. Zero is false; all other
3. The empty string ( '' ) is false; all other strings are normally true.
4. The one exception: since numbers and strings are equivalent, the string form of zero, '0' , has the same value as its numeric form: false.
So, if your scalar value is undef , 0 , '' , or '0' , it's false. All other scalars are true—including all of the types of scalars that we haven't told you about yet.
If you need to get the
if (! $is_bigger) { # Do something when $is_bigger is not true }
At this point, you're probably wondering how to get a value from the keyboard into a Perl program. Here's the simplest way: use the line-input operator, <STDIN> . [24] Each time you use <STDIN> in a place where a scalar value is expected, Perl reads the
[24] This is actually a line-input operator working on the filehandle STDIN , but we can't tell you about that until we get to filehandles (in Chapter 11 ).
[25] To be honest, it's normally your system that waits for the input; Perl waits for your system. Although the details depend upon your system and its configuration, you can
The string value of <STDIN> typically has a newline character on the end of it. [26] So you could do something like this:
[26] The exception is if the standard input stream somehow runs out in the middle of a line. But that's not a proper text file, of course!
$line = <STDIN>; if ($line eq "\n") { print "That was just a blank line!\n"; } else { print "That line of input was: $line"; } But in practice, you don't often want to keep the newline, so you need the chomp operator.