In Perl, there are contexts that affect the behavior of operators and functions:
scalar) — the expression is evaluated as a single value.list) — the expression is evaluated as a list of values.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
What value does the function
keys %hashreturn 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')
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 savedThis complicated debugging — the function worked, but the file was not saved anywhere, and errors were not caught.