home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeLearning Perl, 3rd EditionSearch this book

2.6. Output with print

It's generally a good idea to have your program produce some output; otherwise, someone may think it didn't do anything. The print( ) operator makes this possible. It takes a scalar argument and puts it out without any embellishment onto standard output. Unless you've done something odd, this will be your terminal display. For example:

print "hello world\n"; # say hello world, followed by a newline

print "The answer is ";
print 6 * 7;
print ".\n";

You can actually give print a series of values, separated by commas.

print "The answer is ", 6 * 7, ".\n";

This is actually a list, but we haven't talked about lists yet, so we'll put that off for later.

2.6.1. Interpolation of Scalar Variables into Strings

When a string literal is double-quoted, it is subject to variable interpolation[55] (besides being checked for backslash escapes). This means that any scalar variable[56] name in the string is replaced with its current value. For example:

[55]This has nothing to do with mathematical or statistical interpolation.

[56]And some other variable types, but we won't see those until later.

$meal = "brontosaurus steak";
$barney = "fred ate a $meal";    # $barney is now "fred ate a brontosaurus steak"
$barney = 'fred ate a ' . $meal; # another way to write that

As you see on the last line above, you can get the same results without the double quotes. But the double-quoted string is often the more convenient way to write it.

If the scalar variable has never been given a value,[57] the empty string is used instead:

[57]This is actually the special undefined value, undef, which we'll see a little later in this chapter. If warnings are turned on, Perl will complain about interpolating the undefined value.

$barney = "fred ate a $meat"; # $barney is now "fred ate a "

Don't bother with interpolating if you have just the one lone variable:

print "$fred"; # unneeded quote marks
print $fred;   # better style

There's nothing really wrong with putting quote marks around a lone variable, but the other programmers will laugh at you behind your back.[58]

[58]Well, it may force a value to be interpreted as a string, rather than a number. In a few rare cases that may be needed, but nearly always it's just a waste of typing.

Variable interpolation is also known as double-quote interpolation, because it happens when double-quote marks (but not single quotes) are used. It happens for some other strings in Perl, which we'll mention as we get to them.

To put a real dollar sign into a double-quoted string, precede the dollar sign with a backslash, which turns off the dollar sign's special significance:

$fred = 'hello';
print "The name is \$fred.\n";    # prints a dollar sign
print 'The name is $fred' . "\n"; # so does this

The variable name will be the longest possible variable name that makes sense at that part of the string. This can be a problem if you want to follow the replaced value immediately with some constant text that begins with a letter, digit, or underscore.[59] As Perl scans for variable names, it would consider those characters to be additional name characters, which is not what you want. Perl provides a delimiter for the variable name in a manner similar to the shell. Simply enclose the name of the variable in a pair of curly braces. Or, you can end that part of the string and start another part of the string with a concatenation operator:

[59]There are some other characters that may be a problem as well. If you need a left square bracket or a left curly brace just after a scalar variable's name, precede it with a backslash. You may also do that if the variable's name is followed by an apostrophe or a pair of colons, or you could use the curly-brace method described in the main text

$what = "brontosaurus steak";
$n = 3;
print "fred ate $n $whats.\n";          # not the steaks, but the value of $whats
print "fred ate $n ${what}s.\n";        # now uses $what
print "fred ate $n $what" . "s.\n";     # another way to do it
print 'fred ate ' . $n . ' ' . $what . "s.\n"; # an especially difficult way

2.6.2. Operator Precedence and Associativity

Operator precedence determines which operations in a complex group of operations happen first. For example, in the expression 2+3*4, do we perform the addition first or the multiplication first? If we did the addition first, we'd get 5*4, or 20. But if we did the multiplication first (as we were taught in math class), we'd get 2+12, or 14. Fortunately, Perl chooses the common mathematical definition, performing the multiplication first. Because of this, we say multiplication has a higher precedence than addition.

You can override the default precedence order by using parentheses. Anything in parentheses is completely computed before the operator outside of the parentheses is applied (just like you learned in math class). So if I really want the addition before the multiplication, I can say (2+3)*4, yielding 20. Also, if I wanted to demonstrate that multiplication is performed before addition, I could add a decorative but unnecessary set of parentheses, as in 2+(3*4).

While precedence is simple for addition and multiplication, we start running into problems when faced with, say, string concatenation compared with exponentiation. The proper way to resolve this is to consult the official, accept-no-substitutes Perl operator precedence chart, shown in Table 2-1.[60] (Note that some of the operators have not yet been described, and in fact, may not even appear anywhere in this book, but don't let that scare you from reading about them in the perlop manpage.)

[60]C programmers: Rejoice! The operators that are available in both Perl and C have the same precedence and associativity in both.

Table 2-2. Associativity and precedence of operators (highest to lowest)

Associativity

Operators

left

parentheses and arguments to list operators

left

->

 

++ -- (autoincrement and autodecrement)

right

**

right

\ ! ~ + - (unary operators)

left

=~ !~

left

* / % x

left

+ - . (binary operators)

left

<< >>

 

named unary operators (-X filetests, rand)

 

< <= > >= lt le gt ge (the "unequal" ones)

 

== != <=> eq ne cmp (the "equal" ones)

left

&

left

| ^

left

&&

left

||

 

.. ...

right

?: (ternary)

right

= += -= .= (and similar assignment operators)

left

, =>

 

list operators (rightward)

right

not

left

and

left

or xor

In the chart, any given operator has higher precedence than all of the operators listed below it, and lower precedence than all of the operators listed above it. Operators at the same precedence level resolve according to rules of associativity instead.

Just like precedence, associativity resolves the order of operations when two operators of the same precedence compete for three operands:

4 ** 3 ** 2 # 4 ** (3 ** 2), or 4 ** 9 (right associative)
72 / 12 / 3 # (72 / 12) / 3, or 6/3, or 2 (left associative)
36 / 6 * 3  # (36/6)*3, or 18

In the first case, the ** operator has right associativity, so the parentheses are implied on the right. Comparatively, the * and / operators have left associativity, yielding a set of implied parentheses on the left.

So should you just memorize the precedence chart? No! Nobody actually does that. Instead, just use parentheses when you don't remember the order of operations, or when you're too busy to look in the chart. After all, if you can't remember it without the parentheses, your maintenance programmer is going to have the same trouble. So be nice to your maintenance programmer.

2.6.3. Comparison Operators

For comparing numbers, Perl has the logical comparison operators that remind you of algebra: < <= == >= > !=. Each of these returns a true or false value. We'll find out more about those return values in the next section. Some of these may be different than you'd use in other languages. For example, == is used for equality, not a single = sign, because that's used for another purpose in Perl. And != is used for inequality testing, because <> is used for another purpose in Perl. And you'll need >= and not => for "greater than or equal to", because the latter is used for another purpose in Perl. In fact, nearly every sequence of punctuation is used for something in Perl.

For comparing strings, Perl has an equivalent set of string comparison operators which look like funny little words: lt le eq ge gt ne. These compare two strings character by character to see whether they're the same, or whether one comes first in standard string sorting order. (In ASCII, the capital letters come before the lowercase letters, so beware.)

The comparison operators (for both numbers and strings) are given in Table 2-3.

Table 2-3. Numeric and string comparison operators

Comparison

Numeric

String

Equal

==

eq

Not equal

!=

ne

Less than

<

lt

Greater than

>

gt

Less than or equal to

<=

le

Greater than or equal to

>=

ge

Here are some example expressions using these comparison operators:

35 != 30 + 5         # false
35 == 35.0           # true
'35' eq '35.0'       # false (comparing as strings)
'fred' lt 'barney'   # false
'fred' lt 'free'     # true
'fred' eq "fred"     # true
'fred' eq 'Fred'     # false
' ' gt ''            # true


Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.