Lesson 6: Reassigning elements of an array


This is a sample array.

1
my @favs = ("Pink Floyd" , "Led Zeppelin", "The Doors");

In the sample array there are 3 elements, 0, 1, and 2

index value
0 Pink Floyd
1 Led Zeppelin
2 The Doors
  • To access/reassign only one element of the array you are reassigning a single scalar variable.
  • The $ and not the @ will be used.
1
2
3
4
5
6
7
8
my @favs = ("Pink Floyd" , "Led Zeppelin", "The Doors");
my $just_one = $favs[2];
print "org: @favs\n";
print "just one: $just_one\n";
 
$favs[2] = "Nirvana";
print "new: @favs\n";
print "just one: $just_one\n";

Output:

%% ./pieces_of_the_array.pl
org: Pink Floyd Led Zeppelin The Doors
just one: The Doors
new: Pink Floyd Led Zeppelin Nirvana
just one: The Doors

Exercises

  1. Write a script in which you create an array and print the array.
  2. Reassign 2 elements to contain new values
  3. Print the array again
  4. Print the last element of the array using the [-1] index.

Print Friendly

2 thoughts on “Lesson 6: Reassigning elements of an array

  1. Length of an array
    If you would like to find the length of the array, use the function scalar. This will return the scalar description of the array, which in perl is the length.
    Code:

    my @favs = ("Pink Floyd" , "Led Zeppelin", "The Doors");
    my $len = scalar @favs;
    print "the length of the array is $len ,"n";
    

    Output:

    %% ./length_of_array.pl
    the length of the array is 3
  2. Adding elements to a distant nonexistent index.
    You can add new elements anywhere in your array, even far off the end of the array.
    Code:

    my @favs = (“Pink Floyd” , “Led Zeppelin”, “The Doors”);
    my $len = scalar @favs;
    print "len:$len @favsn";
    $favs[20] = "Nirvana";
    $len = scalar @favs;
    print "len after adding a 20th element:$lenn";
    

    Output:

     %%./array.pl
    len:3 Pink Floyd Led Zeppelin The Doors
    len after adding a 20th element:21

    The elements between 3 and 20 are empty.

Leave a Reply

Your email address will not be published. Required fields are marked *