Lesson 8 of 15

Arrays

Arrays

Arrays in Perl are ordered lists of scalars, prefixed with @:

my @fruits = ("apple", "banana", "cherry");

Accessing Elements

Use $ (scalar) to access a single element by index (0-based):

say $fruits[0];   # apple
say $fruits[1];   # banana
say $fruits[-1];  # cherry (last element)

Array Length

my $len = scalar(@fruits);   # 3

Modifying Arrays

push @fruits, "date";       # add to end
my $last = pop @fruits;     # remove from end
unshift @fruits, "avocado"; # add to front
my $first = shift @fruits;  # remove from front

Your Task

Create an array of three numbers, push a fourth, then print each element on its own line using a foreach loop.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.