Double-quoted strings use interpolation and escaping – unlike single-quoted strings. To double-quote a string, use either double quotes "
or the qq
operator.
my $greeting = "Hello!\n";
print $greeting;
# => Hello! (followed by a linefeed)
my $bush = "They misunderestimated me."
print qq/As Bush once said: "$bush"\n/;
# => As Bush once said: "They misunderestimated me." (with linefeed)
The qq
is useful here, to avoid having to escape the quotation marks. Without it, we would have to write...
print "As Bush once said: \"$bush\"\n";
... which just isn't as nice.
Perl doesn't limit you to using a slash /
with qq
; you can use any (visible) character.
use feature 'say';
say qq/You can use slashes.../;
say qq{...or braces...};
say qq^...or hats...^;
say qq|...or pipes...|;
# say qq ...but not whitespace. ;
You can also interpolate arrays into strings.
use feature 'say';
my @letters = ('a', 'b', 'c');
say "I like these letters: @letters.";
# => I like these letters: a b c.
By default the values are space-separated – because the special variable $"
defaults to a single space. This can, of course, be changed.
use feature 'say';
my @letters = ('a', 'b', 'c');
{local $" = ", "; say "@letters"; } # a, b, c
If you prefer, you have the option to use English
and change $LIST_SEPARATOR
instead:
use v5.18; # English should be avoided on older Perls
use English;
my @letters = ('a', 'b', 'c');
{ local $LIST_SEPARATOR = "\n"; say "My favourite letters:\n\n@letters" }
For anything more complex than this, you should use a loop instead.
say "My favourite letters:";
say;
for my $letter (@letters) {
say " - $letter";
}
Interpolation does not work with hashes.
use feature 'say';
my %hash = ('a', 'b', 'c', 'd');
say "This doesn't work: %hash" # This doesn't work: %hash
Some code abuses interpolation of references – avoid it.
use feature 'say';
say "2 + 2 == @{[ 2 + 2 ]}"; # 2 + 2 = 4 (avoid this)
say "2 + 2 == ${\( 2 + 2 )}"; # 2 + 2 = 4 (avoid this)
The so-called "cart operator" causes perl to dereference @{ ... }
the array reference [ ... ]
that contains the expression that you want to interpolate, 2 + 2
. When you use this trick, Perl builds an anonymous array, then dereferences it and discards it.
The ${\( ... )}
version is somewhat less wasteful, but it still requires allocating memory and it is even harder to read.
Instead, consider writing:
say "2 + 2 == " . 2 + 2;
my $result = 2 + 2; say "2 + 2 == $result"