ProgrammingBackend Perl Developer

What are the ways to interpolate variables and expressions in Perl strings, and what should be considered when using them?

Pass interviews with Hintsage AI assistant

Answer

Perl supports two forms of string literals — double ("), and single (') quotes. Inside double-quoted strings, interpolation occurs: variables and special characters like \n, \t are replaced with their values. In single quotes, there is no interpolation — the content is taken literally.

Example:

my $name = "Alex"; print "Hello, $name! "; # Hello, Alex! print 'Hello, $name! '; # Hello, $name! # Expression interpolation is possible through curly braces: my $i = 10; print "i + 5 = @{[$i + 5]} "; # i + 5 = 15

Features and nuances:

  • Remember to escape variables if letters follow them; otherwise, Perl will think it's part of the variable name.
  • For complex expressions, use @{[ ... ]} inside an interpolating string – this is a safe way to insert the result of an expression into a string.

Trick question

In what cases will variables inside a double-quoted string not be interpolated?

Answer: When the variable is escaped (\$var), inside single quotes, or if the syntax with curly braces is used incorrectly, or if the variable name is not limited by braces and there is "concatenation" of the variable name with letters.

my $world = 'earth'; print "Hello, $worlds! "; # ERROR: There is no variable $worlds, but $world + letter s

Examples of real mistakes due to ignorance of the nuances of the topic


Story

In a large project, they used strings with variables for logging:

my $file = '/tmp/data'; print LOG 'File: $file

';


They expected to see the file path, but the log contained the literal text `$file`, as single quotes were used. The problem was noticed after going into production.

Story

One developer inserted a variable inside a string without curly braces:

my $user = "bob"; print "User: $user21

";


It was expected to output `bob21`, but the interpreter started looking for the variable `$user21` (which did not exist). This caused an empty value in reports.

Story

To display the result of an expression inside a string, the following code was used:

my $a = 3; print "Sum: $a+5

"; # Expected: 'Sum: 8', got: 'Sum: 3+5'


Indeed, interpolation only considers variables; expressions are inserted literally. You need to work through @{[ ... ]}.