ProgrammingPerl Developer

Explain how array, hash, and scalar interpolation works in Perl for different types of strings, and what dangers are associated with this mechanism.

Pass interviews with Hintsage AI assistant

Answer

In Perl, interpolation (variable substitution) is supported in double quotes ("") and certain templates (e.g., heredoc). Scalars are interpolated simply:

my $name = 'Bob'; print "Hello, $name! "; # Hello, Bob!

Arrays in double quotes become a string after substitution, with elements separated by the character $" (by default — a space):

my @items = ('a','b','c'); print "List: @items "; # List: a b c

Hashes are substituted as a key=>value string, separated by the character $;:

my %h = (x => 1, y => 2); print "Hash: %h "; # Hash: x1y2 (may vary)

In single quotes (' ') nothing is interpolated — the string is output literally.

It is also possible to use complex expressions for interpolation through curly braces:

print "${name}_test "; # Bob_test

The danger lies in accidental interpolation of special characters and the differing behavior of arrays, hashes, and scalars.


Trick Question

Why does the string "Total: $total$val" sometimes work incorrectly?

Common answer: "Everything is substituted as it is!"

Correct answer:

The string "Total: $total$val" can only correctly substitute the variable $total, the variable $val may not be recognized or Perl may interpolate the wrong range if variable names are similar. To avoid ambiguity, use curly braces:

print "Total: ${total}${val} ";

History


History 1

In the reports, the total string looked like this: "Total: $sum rub." After adding the variable $rub to the code, the string became "Total: $sum$rub", resulting in interpolation working only for $sum$, while $rub was skipped, leading to warnings. No one understood until they saw an empty string in the output.


History 2

When forming an SQL query, array interpolation through @values was used without join: "IN (@values)". This resulted in a string with a space separator instead of the expected comma-separated list. The outcome — an SQL error and incorrect selection.


History 3

To output the list of hash keys, %h was used in the string: "Keys: %h". As a result, a concatenated key-value string was produced instead of a nice list of keys. It should have been: join ", ", keys %h.