1. Perl
  2. Syntax
  3. here

Understand Perl context

Perl has a concept called context. Context means context, and there are the following two contexts.

The context evaluated as a scalar is called a scalar context, and the context evaluated as a list is called a list context.

As an example, localtime function returns a string that displays the date/time in the scalar context, and the date/time information in the list context. Is listed and returned.

# Scalar context
$date_string = localtime;

# List context
@date_info = localtime;

To give another example, an array returns the number of arrays in a scalar context and a list of elements in a list context.

# Scalar context
$count = @values;

# List context
@elements = @values;

A detailed explanation of the list is given below.

Scalar context

Here are some places that are evaluated as scalar contexts.

Assignment to a scalar variable

Assignment to a scalar variable is a scalar context. When the array is evaluated in scalar context, it returns the length of the array.

my $num = @values;

Comparison operator term

The left and right terms of comparison operator are scalar contexts.

$x <@values
$x == @values

I often see it in the loop of for statement.

for (my $i = 0; $i < @nums; $i++) {
  ...
}

if condition part

The conditional part of if is the scalar context. In the following, @values is evaluated in scalar context, so it returns the number of arrays.

if (@values) {
  ...
}

A detailed explanation of the scalar context is given below.

List context

Here's where it's evaluated as a list context.

Assignment to an array

Assignment to array is a list context.

my @values2 = @values;

List

Inside list is the list context.

(@values);

Subroutine arguments

The argument of subroutine is the list context.

func (@values);

A detailed explanation of the list context is given below.

Example

This is an example to understand the scalar context and list context.

use strict;
use warnings;

# Scalar context and list context

print "1: Know the meaning of the context with the localtime function.\n";
my $scalar;
my @list;

# Since the left side is scalar, it is for scalar
# The return value of is returned.
$scalar = localtime;
                      
# The left side is an array, so it's for a list
# The return value of is returned.
@list = localtime;

print "formatted date\n in scalar context",
  "'$scalar'\n\n";

print "In list context, a list of date and time values \n".
  join(',', @list). "\n\n";

Perl functions can return a scalar return where a scalar is required and a list return where a list is required.

The distinction between a scalar context and a list context is naturally remembered as you touch Perl. Here is an example. If the left side is a scalar, it is a scalar context, and if the left side is an array, it is a list context.

Related Informatrion