perl

What is the purpose of references in Perl?


I'm new to Perl; this is my second class on the topic.

I understand how to use references in Perl (at a basic level), but I fail to understand why. Here's an example introducing references in the textbook, with my added comments.

$array_ref = ["val1", "val2", "val3"]; #create an array reference
print("$$array_ref[1]\n"); #immediately dereference it to print the second element

Why would you use the reference, rather than writing:

@array_name = ("val1", "val2", "val3"); #create an array
print("$array_name[1]\n"); #print the second element

If there is no advantage to using a reference in this case, could you provide an example where it would make a difference?


Solution

  • You wouldn't use a reference there.

    Values of arrays and hashes can only be scalars, so you'd use a reference to store an array or hash into one of those.

    push @a, \@b;
    

    Only a list of scalar can be passed to a subroutine, so you'd use a reference to pass an array or hash to one of those.

    f(\@a, \@b);
    

    Only a list of scalar can be returned by a subroutine, so you'd use a reference to return an array or hash.

    return ( \@a, \@b );
    

    IO objects and (until recently) regex objects cannot be stored directly in a variable. References are used there.

    open(my $fh, '<', $0) or die $!;
    print(ref($fh), "\n");
    

    etc