hoopajoo.net
Brackets, [], and array references
Brackets, [], and array references
⇐ Back to Data: Lists, Scalars, and Hashes oh my!

Questions, comments, or corrections? Send me a message.

Brackets are used to create and modify array references. Array references are important because they reduce memory using subroutines because a copy of the data is not passed, just a reference, and the subroutine can modify the data in place. To make a simple array reference use the \ just like any other reference. Let's say we have the array:

@myarr = ( 'red', 'green', 'blue' );
The array reference to that is:
$arr_ref = \@myarr;
Now you can pass the $arr_ref to a subroutine and it can modify @myarr directly. To access elements in the array reference, you use square brackets:
$arr_ref -> [ 0 ] == $myarr[ 0 ];
$arr_ref -> [ 1 ] == $myarr[ 1 ];
... etc
The other thing you can do with brackets is create an array reference without first creating an array. To create the same array reference as above, you would do this:
$arr_ref = [
  'red',
  'green',
  'blue'
];
Any you have an array reference with the same contects (data wise) as the first example.