O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required