ProgrammingPerl Developer/Backend Developer

How do contexts work in Perl (scalar, list, and void)? Provide examples where the behavior of the code depends on the choice of context.

Pass interviews with Hintsage AI assistant

Answer

In Perl, there are contexts that affect the behavior of operators and functions:

  • Scalar (scalar) — the expression is evaluated as a single value.
  • List (list) — the expression is evaluated as a list of values.
  • Void — the result is not used.

Functions and operators can return different results depending on the context.

Examples:

my @arr = (1, 2, 3); my $count = @arr; # scalar context: $count = 3 my @copy = @arr; # list context: the entire array is copied my $line = <STDIN>; # reads a single line (scalar) my @lines = <STDIN>; # reads all lines (list)

Context can be explicitly set using the scalar() function:

my $last_idx = scalar @arr; # force scalar context

Trick Question

What value does the function keys %hash return in scalar context?

Answer: It returns the number of elements in the hash, not a list of keys as in list context.

my %h = (a=>1, b=>2); my $num = keys %h; # $num = 2 my @keys = keys %h; # @keys = ('a', 'b')

Examples of real errors due to lack of understanding of the nuances of the topic


Story

In one project, the number of elements in an array was being counted:

my @items = get_items(); my $cnt = @items;

Later someone decided to assign $cnt = get_items();, not understanding that the function returns a list — now it always got only one (the first) returned value, not the number of elements.


Story

When reading lines from a file:

my $lines = <FILE>;

Expecting to get the whole file, only the first line was obtained — they did not consider that in scalar context only a single line is returned.


Story

A developer called a function in void context, not using the returned value:

open_my_file(); # the function returns a descriptor, but it was not saved

This complicated debugging — the function worked, but the file was not saved anywhere, and errors were not caught.