perl lists and arrays

w‮.ww‬theitroad.com

In Perl, an array is a variable that can hold an ordered list of scalar values. Arrays are denoted by the @ sigil, and can be declared using the my keyword. Here's an example:

my @numbers = (1, 2, 3, 4, 5); # declare an array of integers
my @names = ("Alice", "Bob", "Charlie"); # declare an array of strings

Arrays in Perl can hold values of different types, including scalars, arrays, and hashes. To access individual elements of an array, you can use the square bracket notation ($array[index]). Array indices start at 0. For example:

my @numbers = (1, 2, 3, 4, 5);
print $numbers[0]; # prints 1
print $numbers[2]; # prints 3

You can also modify individual elements of an array by assigning a new value to the corresponding index:

my @numbers = (1, 2, 3, 4, 5);
$numbers[2] = 10;
print @numbers; # prints 1 2 10 4 5

In addition to arrays, Perl also supports lists, which are similar to arrays but are not stored in a variable. Lists can be used as arguments to functions or as values returned from functions. For example:

my @numbers = (1, 2, 3);
my $sum = sum(@numbers); # pass array as list to sum function
sub sum {
  my $total = 0;
  foreach my $number (@_) {
    $total += $number;
  }
  return $total;
}

In summary, arrays in Perl are used to hold ordered lists of scalar values, and are denoted by the @ sigil. They can hold values of different types, and can be accessed and modified using square bracket notation. Lists are similar to arrays but are not stored in a variable, and can be used as arguments or return values for functions.