#!perl
use strict;
# this creates a simple list named 'array'
my @array = ('1','2','3','blue','red');
# this creates a pointer or reference to the list
# named 'array'. This new reference (a variable)
# is named 'array_reference'.
my $array_reference = \@array;
# Conceptually, you might imagine that the variable
# is named 'array_reference' and it holds the value
# 'array'.(see NOTE below)
# So, just as you would refer to the original array as
# @array you can also refer to it as an array whose name
# is 'array'.
# or,..... @$array_reference
# | |
# an array |
# |
# whose name is the contents of $array_reference
# So, just as you can print 'blue' like
print "BLUE: $array[3]\n";
# You can also print 'blue' like.
print "COLOR: $$array_reference[3]\n";
# So, why is this useful?
# A simple example.......
# You don't have to create the real array multiple times.
# This becomes significant if the array is huge. If you did
# not use a reference, you would have to pass the entire
# array into a sub routine which would duplicate it.
&print_array(@array);
sub print_array {
# we just duplicated the array, it now exists as
# @array (the original) and as @_ (local to this sub)
foreach (@_) { print "ELEMENTS OF A SECOND ARRAY: $_\n"; }
}
&print_array_by_ref($array_reference);
sub print_array_by_ref {
# we did not duplicate the array.
# instead we passed a pointer to the original array
# and de-reference the reference to get at the
# original array.
my $reference = shift;
foreach (@$reference) { print "ELEMENTS OF THE ORIGINAL ARRAY: $_\n"; }
}
# NOTE: In reality it does not, but conceptually this helps
# when trying to figure out what a reference is.
# What it really does is create of pointer to the memory
# location of the original array. Actually, I think it
# points to the symbol table, but that is beyond this
# discussion.....