
| Contents |
|||||||||||||||||||||||||||||
| [an error occurred while processing this directive] |
2.3.1 Scalar Interpolation
Recall that when we discussed double-quotes strings
(see section 2.1.3 Double-quoted Strings), we noted that we had to backslash the
Interpolation of scalar variables allows us to insert the value of a scalar variable right into a double-quoted string. In addition, since Perl largely does all data conversion necessary, we can often use variables that have integer and float values and interpolate them right into strings without worry. In most cases, Perl will do the right thing. Consider the following sample code: use strict; my $friend = 'Joe'; my $greeting = "Howdy, $friend!"; # $greeting contains "Howdy, Joe!" my $cost = 20.52; my $statement = "Please pay \$$cost.\n"; # $statement contains "Please pay $20.52.\n" my $debt = "$greeting $statement"; # $debt contains "Howdy, Joe! Please pay $20.52.\n" As you can see from this sample code, you can build up strings by placing scalars inside double-quotes strings. When the double-quoted strings are evaluated, any scalar variables embedded within them are replaced with the value that each variable holds.
Note in our example that there was no problem interpolating
Interpolation is not only used when assigning to other scalar
variables. You can use a double-quoted string and interpolate it in any
context where a scalar expression is appropriate. For example, we could
use it as part of the This example produces the output:#!/usr/bin/perl use strict; use warnings; my $owner = 'Elizabeth'; my $dog = 'Rex'; my $amount = 12.5; my $what = 'dog food'; print "${owner}'s dog, $dog, ate $amount pounds of $what.\n"; Elizabeth's dog, Rex, ate 12.5 pounds of dog food.
Notice how we are able to build up a large string using four variables,
some text, and a newline character, all contained within one
interpolated double-quoted string. We needed only to pass one
argument to
You may have noticed by now that we did something very odd with
In many cases when using interpolation, Perl requires us to do this.
Certain characters that follow scalar variables mean something special
to Perl. When in doubt, however, you can wrap the name of the scalar in
curly braces (as in Note that this can also be a problem when an interpolated scalar variable is followed by alpha-numeric text or an underscore. This is because Perl cannot tell where the name of the scalar variable ends and where the literal text you want in the string begins. In this case, you also need to use the curly braces to make things clear. Consider: use strict; my $this_data = "Something"; my $that_data = "Something Else "; print "_$this_data_, or $that_datawill do\n"; # INVALID: actually refers # to the scalars $this_data_ # and $that_datawill print "_${this_data}_, or ${that_data}will do\n"; # CORRECT: refers to $this_data and $that_data, # using curly braces to make it clear
|