Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of references in Perl?

Tags:

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?

like image 352
philipthegreat Avatar asked Oct 30 '25 22:10

philipthegreat


2 Answers

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

like image 138
ikegami Avatar answered Nov 02 '25 11:11

ikegami


Reference in Perl help in making complex data-structures. Like multidimensional array in Perl can be implemented using reference:

my $a = [
      [1, 2],
      [3, 4],
];

print $a->[1]->[0];  #Will print 3

With the help reference even you can build complex data structures easily, like:

my $employee = {
    name =>"xyz",
    age => 22,
    contactnums => [ 9xxxxxxxx, 7xxxxxxxx ],
    addresses => {
                    office => 'something1',
                    residential => 'something2',
                    permanent => 'something3',
                 }
    id => '12121',
};
like image 37
vips Avatar answered Nov 02 '25 11:11

vips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!