1. Perl
  2. Syntax
  3. here

Variable expansion

Perl has a feature called variable expansion that allows you to use variable in strings. The string must be enclosed in double quotes.

my $str2 = "AAA $str1 CCC";

Since you can use variable directly in string, variable It's easier than writing using the href="/blog/20080221120361.html">string concatenation operator. Let's use it positively.

Let's write an example of variable expansion.

my $animal = 'cat';

my $message = "I like $animal";

"$Animal" is interpolated and "$message" becomes "I like cat".

When a string follows variable expansion

When expanding a variable, if a string follows the variable, that string will also be recognized as part of the variable name. In such a case, use "{}" after $to enclose the variable name.

my $animal = 'cat';

my $message = "dog ${animal} mouse";

It will be correctly expanded as "dog cat mouse".

Array variable expansion

Array can also be interpolated. If the array is variable-expanded, the elements are concatenated with blanks.

my @animals = ('dog', 'cat', 'mouse');

my $message = "I like @animals";

"$Message" expands to "I like dog cat mouse".

Subroutine variable expansion

Subroutine is not a variable, so it cannot be interpolated. It is smart to assign to a variable and then use the variable expansion function.

my $total = sum (1, 2);
my $message = "Number is $total";

Variable expansion in here document

You can also use variable interpolation in Here Document. Enclosing the terminating string in double quotes makes it easier to understand the intention of variable expansion.

my $animal = 'cat';

my $message = << "EOS";
I love you.
I like $animal.
EOS

Related Informatrion