1. Creating the 2D Array
You define the main array using parentheses
(), and create the inner arrays (the rows) using square brackets []. The square brackets create anonymous array references.my @array = (
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
);
2. Accessing Elements
To access a specific value, you use the scalar sigil
$ (since you are fetching a single value) followed by the array name and the row and column indices in consecutive square brackets: $array[row_index][column_index].my $top_left = $array[0][0]; # Accesses the first element (1)
my $bottom_right = $array[2][2]; # Accesses the third element of the third row (9)
3. Iterating and Printing
When you loop through the main array, each item is an array reference. You must dereference it (using
@$_) to access the actual values inside the row.print "@$_\n" for @array;
This loop takes each row reference (
---------------------
$_), dereferences it to an array (@$_), interpolates it into a string with spaces between elements, and prints it with a newline.---------------------
| my @array = ([1, 2, 3], [4, 5, 6], [7, 8, 9]); my $top_left = $array[0][0]; # 1 my $bottom_right = $array[2][2]; # 9 print "@$_\n" for @array; |
No comments:
Post a Comment