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 below1: Simplest form, returns the @data;
2: pass the sub the reference to the arraymy @data = prepData(); for my $item (@data) { #format and output } sub prepData { my @data; #create array of hashes return @data; }
3: return the reference to the arraymy @data; prepData(\@data); for my $item (@data) { #format and output } sub prepData { my $refData = shift; #do data generation; }
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
In reply to references best practice by bende
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |