Passing an array reference in perl
In perl, when you declare a variable and assign it a value, and then later pass that variable into a function, the function is getting a copy of the variable, manipulating it, and then passing back some result. This may be fine for most operations, but if you are operating on a large array of values, it isn’t very efficient to pass in an entire copy of the array each time you call a function. Plus, you might want to make modifications to the array within the function and retain those changes outside of the function once it has run. You can do this by passing in a reference (or pointer) to the array when calling your function. This way, the function is performing its work on the actual array and all changes made to it while in the function affect the contents of your original array.
So, to pass an array reference in perl we go like this:
## first we create our array
my @aTest = ();## here's the function that will take it
sub myFunction {
(
$aTestRef
) = @_;
foreach my $item ( @{$aTestRef}) { print "item: $item\n";
}
}
## and here's how we call the function
myFunction (\@aTest);
So to reference an array, or a scalar or hash, for that matter - you backslash the variable when you pass it to a function. That way, rather than passing in a copy of the entire array, you are only passing a pointer to the original array.Then, within the function, you reference it normally, but put the reference to the array, etc. where you normally would just have the variable’s name. For example @{$test} — this would get us the array pointed to by reference $test. Easiest way to think of it is to expand from the inside out - so $test is the pointer to the variable, and then ${$test} or @{$test} or ${$test}{’value1′} is accessing what the pointer is pointing to. Each of the previous three examples are for a scalar, an array, and a hash, respectively.
