[Wellington-pm] The Perl Way: References & subroutines

Andrew Chilton andy at catalyst.net.nz
Sun Feb 20 19:58:12 PST 2005


Hi Kevin,

Kevin Dorne writes:
 > I'm writing a subroutine that fetches some data externally and returns it as a hash.  I'm just not sure the best way to do this in Perl.  For example,
 > 
 > my %nxt = fetch_next();
 > sub fetch_next {
 >   ...
 >   my %msg = ( 'a' => 'b', ); 
 >   return %msg;
 > }

This will return %msg in a (big?) long list back to the caller. It is 'flattened' on the way out of fetch_next() but then restored/assigned to the %nst hash. This takes a while since you'll have to copy the whole list.

 > vs
 > my $msg = fetch_next();
 > sub fetch_next {
 >   ...
 >   my $msg = { 'a' => 'b', };
 >   return $msg;
 > }

This creates the hash as it goes along and the only thing it passes back to $msg is the reference to the hash. This would be quicker than the above.

 > vs
 > my %msg;
 > fetch_next(\%msg);
 > sub fetch_next {
 >   my $msg = shift;
 >   ...
 > }

I would suggest using (2) unless all of this code happens to be in a bigger loop. In which case (3) would save re-creating the hash everytime and (2) would be slightly slower.

Depending on how big %msg/$msg is, I wouldn't be too worried. I'd say to go for (2) or (3) though. My preference would be (2) unless it was all in a loop itself.

Andy



More information about the Wellington-pm mailing list