Документация
HTML CSS PHP PERL другое

Section 2.5.  Output with print

 
Previous
Table of Contents
Next

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[Section 2.5.  Output with print] name in the string is replaced with its current value:

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

[Section 2.5.  Output with print] And some other variable types, but you 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,[*] 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.[Section 2.5.  Output with print] 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.

[Section 2.5.  Output with print] Well, it may interpret the value as a string, rather than as a number. In rare cases, that may be needed, but nearly always it's 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.[Section 2.5.  Output with print] 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 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:

[Section 2.5.  Output with print] 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 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.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)

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 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

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

    Previous
    Table of Contents
    Next
    © 2000- NIV