- When a string literal is double quoted, it is subject to
variable interpolation .
- The terms Variable Interpolation are simply big words
programmers use to impress each other. If they said variable
expansion or variable substitution it would not sound
nearly impressive enough.
- Example:
$MyName = "Reepicheep";
$Greeting = "Hello $MyName\n"; # Greeting is now "Hello Reepicheep\n"
- This is only done once. If the result of the substitution
contains a $ character, no further substitutions are
performed.
- If you don't wish the substitution to be performed, use the
\$ in place of your $ characters.
Alternately you could concatenate single quoted strings to do the same
thing, as single quoted strings are not variable interpolated.
- Perl decides what constitutes a variable by being greedy... it
tries to find the longest possible variable match. You can use the
curly braces to explicitly tell Perl which variable is the one you
want.
- Example:
$Greeting = "Hello";
$GreetingFormal = "Good Day";
# Make string "Good Day Reepicheep\n"
$GreetingStringOne = "$GreetingFormal Reepicheep\n";
# Make string "HelloFormal Reepicheep\n"
$GreetingStringTwo = "${Greeting}Formal Reepicheep\n";
- You could use concatenation to remove any ambiguity in variable
names as well.
- Example:
$Greeting = "Hello";
$GreetingFormal = "Good Day";
# Make string "Good Day Reepicheep\n"
$GreetingStringOne = "$GreetingFormal Reepicheep\n";
# Make string "HelloFormal Reepicheep\n"
$GreetingStringTwo = "$Greeting" . "Formal Reepicheep\n";