# Perl Variable Context

PERLServer Side ProgrammingProgramming Scripts

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 −

## Example

Live Demo

#!/usr/bin/perl
@names = ('John Paul', 'Lisa', 'Kumar');
@copy = @names;
$size = @names; print "Given names are : @copy\n"; print "Number of names are :$size\n";

## Output

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
1Scalar
Assignment to a scalar variable evaluates the right-hand side in a scalar context.
2List
Assignment to an array or a hash evaluates the right-hand side in a list context.
3Boolean
Boolean context is simply any place where an expression is being evaluated to see whether it's true or false.
4Void
This context not only doesn't care what the return value is, but it also doesn't even want a return value.
5Interpolative
This context only happens inside quotes or things that work like quotes.
Published on 28-Nov-2019 08:11:25