Section 2.5. Output with print

2.5. 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:

     print "hello world\n"; # say hello world, followed by a newline           print "The answer is ";     print 6 * 7;     print ".\n"; 

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

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

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

2.5.1. Interpolation of Scalar Variables into Strings

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

[] And some other variable types, but you wont 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,[*] the empty string is used instead:

[*] This is the special undefined value, undef, which you'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 the one lone variable:

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

There's nothing wrong with putting quote marks around a lone variable, but the other programmers will laugh at you behind your back.[] 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.

[] Well, it may interpret the value as a string, rather than as a number. In rare cases, that may be needed, but nearly always its just a waste of typing.

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.[] As Perl scans for variable names, it would consider those characters as additional name characters, which is not what you want. Perl provides a delimiter for the variable name in a manner similar to the shell. Enclose the [] There are some other characters that may be a problem as well. If you need a left square bracket or a left curly brace after a scalar variables 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.5.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 you perform the addition first or the multiplication first? If you did the addition first, you'd get 5*4, or 20. But if you did the multiplication first (as you were taught in math class), you'd get 2+12, or 14. Fortunately, Perl chooses the common mathematical definition, performing the multiplication first. Because of this, you 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 (as you learned in math class). So if you want the addition before the multiplication, you can say (2+3)*4, yielding 20. If you wanted to demonstrate that multiplication is performed before addition, you could add a decorative but unnecessary set of parentheses, as in 2+(3*4).

While precedence is simple for addition and multiplication, you start running into problems when faced with 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-2.[*] (Some of the operators have not yet been described and may not appear anywhere in this book, but don't let that scare you from reading about them in the perlop manpage.)

[*] 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)




Parentheses and arguments to list operators




++ -- (autoincrement and autodecrement)




\ ! ~ + - (unary operators)


=~ !~


* / % x


+ - . (binary operators)


<< >>


Named unary operators (-X filetests, rand)


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


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




| ^






.. ...


?: (ternary)


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


, =>


List operators (rightward)






or xor

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

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 does that. Instead, 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 because you may be that person one day.

2.5.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. You'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. The single = sign is used for assignment. != is used for inequality testing because <> is used for another purpose in Perl. 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. So, if you get writers' block, let the cat walk across the keyboard and debug what results.

For comparing strings, Perl has an equivalent set of string comparison operators that look like funny little words: lt le eq ge gt ne. These compare two strings character by character to see if they're the same, or if 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





= =


Not equal



Less than



Greater than



Less than or equal to



Greater than or equal to



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 

Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2003
Pages: 232

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: