Friday, November 21, 2008

Perl references to return values

Today I was working on some Perl code that needs to take an array returned from one function, make a reference to that array, and pass the reference to another function. It seemed like a simple enough thing to do. I've been doing Perl programming for seven years. After trying a few things and hitting failure, I pulled out the O'Reilly book Programming Perl and read the chapters on references and on subroutines. You can make references to anything: scalars, arrays, file handles, subroutines. But it seemed you can't just take a sub-routine's return value and make a reference to it.

A little poking around on Google turned up an indication that I'm not missing something. There may not be a way to do exactly what I'm trying to do according to a post on Perlmonks.org. So instead of making a reference to a sub-routine's return value, you have to make a reference to a copy of the return value.

Here is the code that demonstrates this:

#!/usr/bin/perl
#From a post on caffeinemakesmesleepy.blogspot.com
# Demonstrate how to take an array return from one function and pass a reference to it into another.

#[] around return_array function makes a reference to a copy of the return value of that function.
# you need the () after return_array or "return_array" gets passed into take_array_ref
take_array_ref([return_array()]);

sub return_array {
my @ret;
push (@ret, 'FOO');
push (@ret, 'BAR');
return @ret;
}

sub take_array_ref {
my $ref = shift;
my $i = 0;
foreach my $value (@$ref) {
$i++;
print "Element #$i: $value\n";
}
}