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.

Interpolation of Scalar Variables into Strings

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

    $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,[51] the empty string is used instead:

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

Get Learning Perl, Fourth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.