In Perl, variables are divided into scalars ($), arrays (@), and hashes (%):
Scalars ($variable) – store a single value (string, number):
my $name = "Ivan"; my $age = 30;
Arrays (@array) – a set of ordered elements (indexed by numbers):
my @fruits = ("apple", "banana", "cherry"); print $fruits[1]; # banana
Hashes (%hash) – a set of key-value pairs (associative array):
my %colors = (red => "#ff0000", green => "#00ff00"); print $colors{"red"}; # #ff0000
Note that accessing an element uses a specific symbol depending on the type of variable:
$array[0] — element of the array$hash{"key"} — value of the hash by keyWhat is the difference between the expressions @array[1,2] and $array[1,2]?
Answer:
@array[1,2]— provides a list of multiple elements from the array (slice).$array[1,2]— incorrect, leads to an error. To access multiple elements of an array, only the slice@array[...]should be used.Example:
my @array = (10, 20, 30, 40); my @slice = @array[1,2]; # (20, 30)
Story
In a logging project, a programmer accessed a hash element using
@colors{"red"}. As a result, it produced not the value of the hash, but a random error because a$is needed for a single value, not@.
Story
In one service, while iterating over the indexes of an array, the correct access was forgotten — instead of
$array[$i],@array$iwas used, leading to warnings and incorrect results.
Story
In an API project, a function was described to take an array as
$args, but an array was passed on the call without the scalar:func(@list). It turned out that this way the elements of the array are "unfolded" into a list, and the function did not work as expected. It was correct to accept the array as@args.