Pointers in Perl

Perl supports references, which are similar to pointers in other languages. They allow you to create complex data structures and pass references to values within your program.

We’ll show how references work in contrast to values with two subroutines: zeroval and zeroref. zeroval takes a scalar value as an argument, so it will receive a copy of the value. zeroval will modify its local copy, but this won’t affect the original variable in the calling scope.

sub zeroval {
    my $ival = shift;
    $ival = 0;
}

zeroref, in contrast, takes a reference to an integer. The $$iref syntax in the subroutine body dereferences the reference to access the actual value. Assigning a value to a dereferenced reference changes the value of the original variable.

sub zeroref {
    my $iref = shift;
    $$iref = 0;
}

Now let’s see how these subroutines work in practice:

use strict;
use warnings;

my $i = 1;
print "initial: $i\n";

zeroval($i);
print "zeroval: $i\n";

# The \$i syntax creates a reference to $i
zeroref(\$i);
print "zeroref: $i\n";

# References can be printed too, but they'll show the memory address
print "reference: ", \$i, "\n";

sub zeroval {
    my $ival = shift;
    $ival = 0;
}

sub zeroref {
    my $iref = shift;
    $$iref = 0;
}

zeroval doesn’t change the $i in the main scope, but zeroref does because it has a reference to the original variable.

When you run this script, you’ll see output similar to this:

$ perl references.pl
initial: 1
zeroval: 1
zeroref: 0
reference: SCALAR(0x55b5a0a1c2c8)

In this example, zeroval doesn’t modify the original $i, while zeroref sets it to 0. The last line prints the memory address of the reference to $i, which will vary each time you run the script.

Perl’s references are powerful and flexible, allowing you to create complex data structures and write more efficient code by avoiding unnecessary copying of large data sets.