bende has asked for the wisdom of the Perl Monks concerning the following question:
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 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
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: references best practice
by kyle (Abbot) on Apr 25, 2008 at 12:23 UTC | |
by amarquis (Curate) on Apr 25, 2008 at 12:44 UTC | |
Re: references best practice
by hipowls (Curate) on Apr 25, 2008 at 11:33 UTC | |
by amarquis (Curate) on Apr 25, 2008 at 18:47 UTC | |
by Haarg (Priest) on Apr 25, 2008 at 22:51 UTC | |
Re: references best practice
by jethro (Monsignor) on Apr 25, 2008 at 15:04 UTC | |
by hsmyers (Canon) on Apr 25, 2008 at 15:50 UTC | |
by roboticus (Chancellor) on Apr 25, 2008 at 18:13 UTC | |
Re: references best practice (wantarray)
by lodin (Hermit) on Apr 25, 2008 at 14:35 UTC | |
Re: references best practice
by sundialsvc4 (Abbot) on Apr 28, 2008 at 21:27 UTC |