Perl Variable Context

Perl treats the same variable differently based on Context, i.e., the situation where a variable is being used. Let's check the following example −


 Live Demo

@names = ('John Paul', 'Lisa', 'Kumar');
@copy = @names;
$size = @names;

print "Given names are : @copy\n";
print "Number of names are : $size\n";


This will produce the following result −

Given names are : John Paul Lisa Kumar
Number of names are : 3

Here @names is an array, which has been used in two different contexts. First, we copied it into another array, i.e., list, so it returned all the elements assuming that context is list context. Next we used the same array and tried to store this array in a scalar, so in this case, it returned just the number of elements in this array assuming that context is scalar context. Following table lists down the various contexts −

Sr.No.Context & Description
Assignment to a scalar variable evaluates the right-hand side in a scalar context.
Assignment to an array or a hash evaluates the right-hand side in a list context.
Boolean context is simply any place where an expression is being evaluated to see whether it's true or false.
This context not only doesn't care what the return value is, but it also doesn't even want a return value.
This context only happens inside quotes or things that work like quotes.