http://qs321.pair.com?node_id=682769

bende has asked for the wisdom of the Perl Monks concerning the following question:

Good Day Everyone
To be honest, im very new to perl (very new to computer science at uni as well!) but i have been using perl and absolutly love it! so please forgive the potential nievity of this question, we've all had to learn at some point.

im currently working my head around references, which i have the basic concept of, but i wanted to ask for your oppinion just to make sure im on the right track. I have shown 3 pieces of code, it is very simple; i have a subroutine to generate data (stored in a library but thats beyond the scope of my question) and then i call this subroutine when i want to output that data somewhere. (CGI, text file etc). The subroutine populates an array of hashes, which is looped through to output. as you can see I am handling the passing of this array in 3 different ways. In 1 I just create the data array in the subroutine and return it. In 2 I create the array first then pass its reference to the subroutine that populates it. In 3 I create the array in the subroutine and return a reference to it. It is my guess that 2 is the most efficient as it does not require copying the array as in 1, and will guarantee that the subroutine is (and any variables used) removed from memory as soon as the sub has finished executing.

my example code below

1: Simplest form, returns the @data;

my @data = prepData(); for my $item (@data) { #format and output } sub prepData { my @data; #create array of hashes return @data; }

2: pass the sub the reference to the array

my @data; prepData(\@data); for my $item (@data) { #format and output } sub prepData { my $refData = shift; #do data generation; }

3: return the reference to the array

my $refData = prepData(); for my $item (@$refData) { #format and output } sub prepData { my @data; #create array of hashes return \@data; }

Many thanks for your help
Ben