References in Perl

Recall that arrays and hashes in Perl are arrays and associative arrays of scalars. This means that Perl does not have arrays of arrays (i.e., matrices). References were introduced in Perl 5 to make up for this shortcoming. A reference is a scalar that can refer to an entire array, and if you have a reference to an array you can recover the array from it. Since a reference is a scalar, you can have an array of references, which is every bit as useful as an array of arrays.

  1. If you put a backslash in front of an array or hash, yet get a reference to it.
    @array = (11..15);
    %hash = ( Jan => 1, Feb => 2 );
    $arrayref = \@array;
    $hashref  = \%hash;
    
  2. To recover an array or a hash from a reference, use @{$ref} or %{$ref}
    @newarray = @{$arrayref};
    %newhash  = %{$hashref};
    
  3. You can use the array @{$ref} and the hash %{$ref} just like any other array or hash. For example, we access the scalars in these arrays.
    ${$arrayref}[1];    # 12
    $newarray[1];       # 12
    ${$hashref}{"Feb"}; # 2
    $newhash{"Feb"};    # 2
    
  4. You can create unnamed (or anonymous) arrays [ items ] and hashes { items } that return references. We create some of these below and assign them to scalar variables.
    $aref = [11,12,13];
    $href = { Mar => 3, Apr => 4 };
    
  5. We can use the unnamed (or anonymous) arrays to create a named array of unnamed arrays (i.e., an array of references).
    @matrix = (
    [ "a00", "a01", "a02" ],
    [ "a10", "a11", "a12" ],
    [ "a20", "a21", "a22" ] 
    );
    
  6. We can access the scalars in this matrix using $matrix[rowindex][columnindex]. Remember: the indexing always starts with zero.
    $matrix[1][2]; # element "a12"
    
  7. References can also be used to pass arrays to subroutines. For example, suppose you want to create a subroutine that takes in two references to arrays of data and processes them somehow.
    # arrays of data
    @xdata = (10,23,31);
    @ydata = (95,77,84);
    
    sub data_processor {
        # read references
        my $xref = shift;
        my $yref = shift;
        # convert references to arrays
        my @x = @{$xref};
        my @y = @{$yref};
        # now process arrays @x and @y
    }
    
    # inputs are references to arrays
    data_processor( \@xdata, \@ydata );
    

Online References