Previous Page Next Page

4.3. The print Function

The print function prints a string or a list of comma-separated words to the Perl filehandle STDOUT. If successful, the print function returns 1; if not, it returns 0.

The string literal \n adds a newline to the end of the string. It can be embedded in the string or treated as a separate string. To interpret backslashes, Perl requires that escape sequences like \n be enclosed in double quotes.

Example 4.1.

(The Script)
1   print "Hello", "world", "\n";
2   print "Hello world\n";

(Output)
1   Helloworld
2   Hello world

Explanation

  1. Each string passed to the print function is enclosed in double quotes and separated by a comma. To print whitespace, the whitespace must be enclosed within the quotes. The \n escape sequence must be enclosed in double quotes for it to be interpreted as a newline character.

  2. The entire string is enclosed in double quotes and printed to standard output.

Example 4.2.

(The Script)
1   print Hello, world, "\n";

(Output)
1   No comma allowed after filehandle at ./perl.st line 1

Explanation

  1. If the strings are not quoted, the filehandle STDOUT must be specified, or the print function will treat the first word it encounters as a filehandle (i.e., the word Hello would be treated as a filehandle). The comma is not allowed after a filehandle; it is used only to separate strings that are to be printed.

Example 4.3.

(The Script)
1   print STDOUT Hello, world, "\n";

(Output)
1   Helloworld

Explanation

  1. The filehandle STDOUT must be specified if strings are not quoted. The \n must be double quoted if it is to be interpreted. It is not a good practice to use unquoted text in this way. Unquoted words are called "Barewords."

    Note: There is no comma after STDOUT.

4.3.1. Quotes

Quoting rules affect almost everything you do in Perl, especially when printing a string of words. Strings are normally delimited by a matched pair of either double or single quotes. When a string is enclosed in single quotes, all characters are treated as literals. When a string is enclosed in double quotes, however, almost all characters are treated as literals with the exception of those characters that are used for variable substitution and special escape sequences. We will look at the special escape sequences in this chapter and discuss quoting and variables in Chapter 5, "What's in a Name."

Perl uses some characters for special purposes, such as the dollar sign ($) and the (@) sign. If these special characters are to be treated as literal characters, they may be preceded by a backslash (\) or enclosed within single quotes (' '). The backslash is used to quote a single character rather than a string of characters.

Example 4.4.

(The Script)
1  $name="Ellie";
2  print "Hello, $name.\n";# $name and \n evaluated
3  print 'Hello, $name.\n';# String is literal; newline not
                           # interpreted

4  print "I don't care!\n";# \n is interpreted in double quotes
5  print 'I don\'t care!', "\n";# Backslash protects single quote
                                # in string "don\'t"
(Output)
2  Hello, Ellie.
3,4  Hello, $name.\nI don't care!
5 I don't care!

It is so common to make mistakes with quoting that we will introduce here the most common error messages you will receive resulting from mismatched quotes and bare words.

Think of quotes as being the "clothes" for Perl strings. If you take them off, you may get a "Bareword" message such as:

Bareword "there" not allowed while "strict subs" in use at try.pl line 3. Execution of program.pl aborted due to compilation errors.

Also think of quotes as being mates. A double quote is mated with a matching double quote, and a single quote with a matching single quote. If you don't match the quotes, if one is missing, the missing quote has "run away." Where did the mate go? You may receive an error like this:

(Might be a runaway multi-line "" string starting on line 3)

Breaking the Quoting Rules
Example 4.5.

(The Script)
    #!/usr/bin/perl
    # Program to illustrate printing literals
1   print "Hello, "I can't go there";  # Unmatched quotes
2   print "Good-bye";

(Output)
Bareword found where operator expected at qtest.plx line 2, near
""Hello, "I"
        (Missing operator before I?)
Bareword found where operator expected at qtest.plx line 3, near
"print "Good"
  (Might be a runaway multi-line "" string starting on line 2)
        (Do you need to predeclare print?)
String found where operator expected at qtest.plx line 3, at end of line
        (Missing semicolon on previous line?)
syntax error at qtest.plx line 2, near ""Hello, "I can't "
Can't find string terminator '"' anywhere before EOF at qtest.plx line 3

Explanation

  1. The string "Hello starts with an opening double quote but is missing the ending quote. This cascades into a barrage of troubles. Perl assumes the double quote preceding the word "I" is the mate for the first quote in "Hello." That leaves the rest of the string "I can't go there" exposed as a bare string. The double quote at the end of the line will be mated with the double quote on the next line. Not good.

  2. The word "Good_bye" is considered a bareword because Perl can't find an opening quote. The double quote at the end of "there" on line 1 has been matched with the double quote at the beginning of "Good-bye," leaving "Good-bye" exposed and bare, with an unmatched quote at the end of the string. Ugh!

4.3.2. Literals (Constants)

When assigning literal values[1] to variables or printing literals, the literals can be represented numerically as integers in decimal, octal, or hexadecimal or as floats in floating point or scientific notation.

[1] Literals may also be called constants, but the Perl experts prefer the term "literal," so in deference to them, we'll use the term "literal."

Strings enclosed in double quotes may contain string literals, such as \n for the newline character, \t for a tab character, or \e for an escape character. String literals are alphanumeric (and only alphanumeric) characters preceded by a backslash. They may be represented in decimal, octal, or hexadecimal or as control characters.

Perl also supports special literals for representing the current script name, the line number of the current script, and the logical end of the current script.

Since you will be using literals with the print and printf functions, let's see what these literals look like. (For more on defining constants, see the "constant" pragma in Appendix A.)

Numeric Literals

Literal numbers can be represented as positive or negative integers in decimal, octal, or hexadecimal (see Table 4.1). Floats can be represented in floating point notation or scientific notation. Octal numbers contain a leading 0 (zero), hex numbers a leading 0x (zero and x), and numbers represented in scientific notation contain a trailing E followed by a negative or positive number representing the exponent.

Table 4.1. Numeric Literals
ExampleDescription
12345Integer
0b1101Binary
0x456fffHex
0777Octal
23.45Float
.234E–2Scientific notation


String Literals

Like shell strings, Perl strings are normally delimited by either single or double quotes. Strings containing string literals, also called escape sequences, are delimited by double quotes for backslash interpretation (see Table 4.2).

Table 4.2. String Literals
Escape SequencesDescriptions (ASCII Name)
\tTab
\nNewline
\rCarriage return
\fForm feed
\bBackspace
\aAlarm/bell
\eEscape
\033Octal character
\xffHexadecimal character
\c[Control character
\lNext character is converted to lowercase
\uNext character is converted to uppercase
\LNext characters are converted to lowercase until \E is found
\UNext characters are converted to uppercase until \E is found
\QBackslash all following nonalphanumeric characters until \E is found
\EEnds upper- or lowercase conversion started with \L or \U
\\Backslash


Example 4.6.

print "This string contains \t\ttwo tabs and a newline.\n" # Double quotes
(Output)
This string containstabs and a newline.

print 'This string contains\t\ttwo tabs and a newline.\n; #Single quotes
(Output)
This string contains\t\ttwo tabs and a newline.\n

Special Literals

Perl's special literals _ _LINE_ _ and _ _FILE_ _ are used as separate words and will not be interpreted if enclosed in quotes, single or double. They represent the current line number of your script and the name of the script, respectively. These special literals are equivalent to the predefined special macros used in the C language.

The _ _END_ _ special literal is used in scripts to represent the logical end of the file. Any trailing text following the _ _END_ _ literal will be ignored, just as if it had been commented. The control sequences for end of input in UNIX is <Ctrl>-d (\004), and <Ctrl>-z (\032) in MS-DOS; both are synonyms for _ _END_ _.

The _ _DATA_ _ special literal is used as a filehandle to allow you to process textual data from within the script instead of from an external file.

Example 4.7.

print "The script is called", _ _FILE_ _, "and we are on line number ",
_ _LINE_ _,"\n";
(Output)
The script is called ./testing.plx and we are on line number 2

Note: There are two underscores on either side of the special literals (see Table 4.3).

Table 4.3. Special Literals
LiteralDescription
_ _LINE_ _Represents the current line number
_ _FILE_ _Represents the current filename
_ _END_ _Represents the logical end of the script; trailing garbage is ignored
_ _DATA_ _Represents a special filehandle
_ _PACKAGE_ _Represents the current package; default package is main


4.3.3. Printing Literals

Now that you know what the literals look like, let's see how they are used with the print function.

Printing Numeric Literals
Example 4.8.

(The Script)
    #!/usr/bin/perl
    # Program to illustrate printing literals
1   print "The price is $100.\n";
2   print "The price is \$100.\n";
3   print "The price is \$",100, ".\n";
4   print "The binary number is converted to: ",0b10001,".\n";
5   print "The octal number is converted to: ",0777,".\n";
6   print "The hexadecimal number is converted to: ",0xAbcF,".\n";
7   print "The unformatted number is ", 14.56, ".\n";
8   $now = localtime(); # A Perl function
9   $name = "Ellie"; # A string is assigned to a Perl variable
10  print "Today is $now, $name.";
11  print 'Today is $now, $name.';

(Output)
1   The price is .
2   The price is $100.
3   The price is $100.
4   The binary number is converted to: 17.
5   The octal number is converted to: 511.
6   The hexadecimal number is converted to: 43983.
7   The unformatted number is 14.56.
10  Today is Sat Mar 24 15:46:08 2007, Ellie.
11  Today is $now, $name.

					  

Explanation

  1. The string The price is $100 is enclosed in double quotes. The dollar sign is a special Perl character. It is used to reference scalar variables (see Chapter 5, "What's in a Name"), not money. Therefore, since there is no variable called $100, nothing prints. Since single quotes protect all characters from interpretation, they would have sufficed here, or the dollar sign could have been preceded with a backslash. But when surrounded by single quotes, the \n will be treated as a literal string rather than a newline character.

  2. The backslash quotes the dollar sign, so it is treated as a literal.

  3. To be treated as a numeric literal, rather than a string, the number 100 is a single word. The dollar sign must be escaped even if it is not followed by a variable name. The \n must be enclosed within double quotes if it is to be interpreted as a special string literal.

  4. The number is represented as a binary number because of the leading 0b (zero and b). The decimal value is printed.

  5. The number is represented as an octal value because of the leading 0 (zero). The decimal value is printed.

  6. The number is represented as a hexadecimal number because of the leading 0x (zero and x). The decimal value is printed.

  7. The number, represented as 14.56, is printed as is. The print function does not format output.

  8. Perl has a large set of functions. You have already learned about the print function. The localtime() function is another. (The parentheses are optional.) This functions returns the current date and time. We are assigning the result to a Perl variable called $now. You will learn all about variables in the next chapter.

  9. The variable $name is assigned the string "Ellie".

  10. When the string is enclosed in double quotes, the print function will display the value of the variables $now and $name.

  11. When the string is enclosed in single quotes, the print function prints all characters literally.

Printing String Literals
Example 4.9.

(The Script)
    #!/usr/bin/perl
1   print "***\tIn double quotes\t***\n";   # Backslash interpretation
2   print '%%%\t\tIn single quotes\t\t%%%\n'; # All characters are
                                              # printed as literals
3   print "\n";

(Output)
1   ***     In double  quotes        ***
2   %%%\t\tIn single quotes\t\t%%%\n
3

Explanation

  1. When a string is enclosed in double quotes, backslash interpretation is performed. The \t is a string literal and produces a tab; the \n produces a newline.

  2. When enclosed within single quotes, the special string literals \t and \n are not interpreted. They will be printed as is.

  3. The newline \n must be enclosed in double quotes to be interpreted. A "\n" produces a newline.

Example 4.10.

(The Script)
    #!/usr/bin/perl
1   print "\a\t\tThe \Unumber\E \LIS\E ",0777,".\n";

(Output)
1   (BEEP)         The NUMBER is 511.

Explanation

  1. The \a produces an alarm or beep sound, followed by \t\t (two tabs). \U causes the string to be printed in uppercase until \E is reached or the line terminates. The string number is printed in uppercase until the \E is reached. The string is is to be printed in lowercase, until the \E is reached, and the decimal value for octal 0777 is printed, followed by a period and a newline character.

Printing Special Literals
Example 4.11.

(The Script)
    #!/usr/bin/perl
    # Program, named literals.perl, written to test special literals
1   print "We are on line number ", _ _LINE_ _, ".\n";
2   print "The name of this file is ",_ _FILE_ _,".\n";
3   _ _END_ _
    And this stuff is just a bunch of chitter–chatter that is to be
    ignored by Perl.
    The _ _END_ _ literal is like Ctrl–d or \004.[a]

(Output)
1   We are on line number 3.
2   The name of this file is literals.perl.

Explanation

  1. The special literal _ _LINE_ _ cannot be enclosed in quotes if it is to be interpreted. It holds the current line number of the Perl script.

  2. The name of this script is literals.perl. The special literal _ _FILE_ _ holds the name of the current Perl script.

  3. The special literal _ _END_ _ represents the logical end of the script. It tells Perl to ignore any characters that follow it.

[a] See the -x switch in Appendix A for discarding leading garbage.

Example 4.12.

(The Script)
    #!/usr/bin/perl
    # Program, named literals.perl2,
    # written to test special literal _ _DATA_ _
1   print <DATA>;
2   _ _DATA_ _
    This line will be printed.
    And so will this one.

(Output)
This line will be printed.
And so will this one.

Explanation

  1. The print function will display whatever text is found under the special literal _ _DATA_ _. Because the special literal _ _DATA_ _ is enclosed in angle brackets, it is treated as a filehandle opened for reading. The print function will display lines as they are read by <DATA>.

  2. This is the data that is used by the <DATA> filehandle. (You could use _ _END_ _ instead of _ _DATA_ _ to get the same results.)

4.3.4. The warnings Pragma and the -w Switch

The -w switch is used to warn you about the possibility of using future reserved words and a number of other problems that may cause problems in the program. (Often, these warnings are rather cryptic and hard to understand if you are new to programming.) Larry Wall says in the Perl 5 man pages, "Whenever you get mysterious behavior, try the -w switch! Whenever you don't get mysterious behavior, try the -w switch anyway."

You can use the -w switch either as a command-line option to Perl, as

perl -w <scriptname>

or after the shbang line in the Perl script, such as

#!/usr/bin/perl -w

A pragma is a special Perl module that hints to the compiler about how a block of statements should be compiled. You can use this type of module to help control the way your program behaves. Starting with Perl version 5.6.0, warnings.pm was added to the standard Perl library; similar to the -w switch, it is a pragma that allows you to control the types of warnings printed.

In your programs, add the following line under the #! line or, if not using the #! line, at the top of the script:

use warnings;

This enables all possible warnings. To turn off warnings, simply add as a line in your script

no warnings;

This disables all possible warnings for the rest of the script.

Example 4.13.

     (The Script)
         #!/usr/bin/perl
         # Scriptname: warnme
     1   print STDOUT Ellie, what\'s up?;

(Output) (At the Command Line)
$ perl -w warnme
  Unquoted string "what" may clash with future reserved word at warnme line 3.
  Backslash found where operator expected at warnme line 3, near "what\"
  Syntax error at warnme line 3, near "what\"
  Can't find string terminator "'" anywhere before EOF at warnme line 3.

					  

Explanation

  1. Among many other messages, the -w switch (see Appendix A) prints warnings about ambiguous identifiers, such as variables that have been used only once, improper conversion of strings and numbers, etc. Since the string Ellie is not quoted, Perl could mistake it for a reserved word or an undefined filehandle. The rest of the error message results from having an unmatched quote in the string.

Example 4.14.

     (The Script)
         #!/usr/bin/perl
         # Scriptname: warnme
     1   use warnings;
     2   print STDOUT Ellie, what\'s up?;

(Output)
Unquoted string "what" may clash with future reserved word at warnme line 3.
Backslash found where operator expected at warnme line 3, near "what\"
Syntax error at warnme line 3, near "what\"
Can't find string terminator "'" anywhere before EOF at warnme line 3.

					  

Explanation

In Perl versions 5.6 and later, the warnings pragma is used instead of the -w switch. The use function allows you to use modules located in the standard Perl library. The warnings pragma sends warnings about ambiguous identifiers. Since the string Ellie is not quoted, Perl could mistake it for a reserved word or an undefined filehandle. The compiler complains because the string is not terminated with a closing quote.

4.3.5. The diagnostics Pragma

This special pragma enhances the warning messages to a more verbose explanation of what went wrong in your program. Like the warnings pragma, it affects the compilation phase of your program, but unlike the warnings pragma, it attempts to give you an explanation that doesn't assume you are an experienced programmer.

Example 4.15.

(The Script)
use diagnostics;
print "Hello there';  # Unmatched quote
print "We are on line number ", _ _LINE_ _,"\n";

(The output)
Bareword found where operator expected at test.plx line 3, near "$now
= "Ellie"
  (Might be a runaway multi-line "" string starting on line 2) (#1)
    (S syntax) The Perl lexer knows whether to expect a term or an
operator.
    If it sees what it knows to be a term when it was expecting to see
    an operator, it gives you this warning.  Usually it indicates that
    an operator or delimiter was omitted, such as a semicolon.

         (Missing operator before Ellie?)
String found where operator expected at test.plx line 3, at end of
line  (#1)
         (Missing semicolon on previous line?)

syntax error at test.plx line 3, near "$now = "Ellie"
Can't find string terminator '"' anywhere before EOF at test.plx line
3 (#2)
    (F) Probably means you had a syntax error.  Common reasons
include:

        A keyword is misspelled.
        A semicolon is missing.
        A comma is missing.
        An opening or closing parenthesis is missing.
print "hello there';
print "We are on line number ", _ _LINE_ _,"\n";

					  

Explanation

In Perl versions 5.6 and later, the diagnostics pragma is used instead of the -w switch or the warnings pragma. This special Perl module sends detailed messages about the problems that occurred in the script. Since the string Hello there does not contain matched quotes, the diagnostics pragma issues a list of all the potential causes for the failed program. The compiler expects the string to be terminated with another double quote.

4.3.6. The strict Pragma and Words

Another pragma we will mention now is the strict pragma. If your program disobeys the restrictions placed on it, it won't compile. If there is a chance that you might have used "bare," i.e., unquoted, words[2] as in Example 4.15, the strict pragma will catch you and your program will abort. The strict pragma can be controlled by giving it various arguments. (See Appendix A for complete list.)

[2] Putting quotes around a word is like putting clothes on the word—take off the quotes, and the word is "bare."

Example 4.16.

(The Script)
    #!/usr/bin/perl
    # Program: stricts.test
    # Script to demonstrate the strict pragma
1   use strict "subs";
2   $name = Ellie;             # Unquoted word Ellie
3   print "Hi $name.\n";

(Output)
$ stricts.test
  Bareword "Ellie" not allowed while "strict subs" in use at
./stricts.test line 5.
  Execution of stricts.test aborted due to compilation errors.

Explanation

  1. The use function allows you to use modules located in the standard Perl library. When the strict pragma takes subs as an argument, it will catch any barewords found in the program while it is being internally compiled. If a bareword is found, the program will be aborted with an error message.

Previous Page Next Page