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.
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.
Now let’s see how these subroutines work in practice:
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:
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.