1. Perl
  2. Operators
  3. here

Perl list

A list is a representation of a sequence of multiple values.

# List
('a', 'b', 'c', 'd')

Lists can be assigned to arrays or hashes for initialization. ..

# Assignment to array
my @array = ('a', 'b', 'c', 'd');

# Assignment to hash
my %hash = ('a', 'b', 'c', 'd');

Difference between array and list

Arrays and lists are similar, but in reality there are some differences.

The first difference is in the linguistic sense. Arrays are variable and lists are notations.

The second is that the values are different when evaluated in scalar context.

Take a look at the following code. What do you think about "$num1" and "$num2"?

# Evaluate list in scalar context
my $num1 = (5, 6, 7);

# Evaluate arrays in scalar context
my @nums = (5, 6, 7);
my $num2 = @nums;

The answer is that "$num1" becomes "7" and $num2 becomes "3".

In a scalar context, evaluating a list returns the "last value in the list", and evaluating an array returns the "number of arrays".

List notation for hashing

A simple notation using "=>" is provided to make assignments to hashes.

# Hash notation
my %hash = (a =>'b', c =>'d');

It has exactly the same meaning as a regular list, only the notation is different. For the string to the left of =>, single quotes can be omitted if it consists only of alphanumeric characters and underscores. The notation that omits single quotes is preferred.

List assignment

You can assign a list by using the list on the left side. You can assign multiple values to multiple variable.

my ($var1, $var2) = (3, 5);

List by receiving command line arguments and receiving arguments in subroutine You can use assignment.

# Receiving command line arguments
my ($var1, $var2) = @ARGV;

# Receiving arguments in a subroutine
sub foo {
  my ($var1, $var2) = @_;

This is used frequently, so be sure to remember it.

String list operator

The string list operator makes it easy to represent a list of strings.

qw(Cat Mouse Dog)

Please refer to the following articles for a detailed explanation of the string list operator.

Automatic initialization with empty list

Arrays and hashes are declared and initialized with an empty list.

# The following is the same
my @nums;
my @nums = ();
# The following is the same
my %score;
my %score = ();

Related Informatrion