[Melbourne-pm] returning hashes and arrays, source filters considered harmful?

Toby Corkindale toby.corkindale at strategicdata.com.au
Thu Feb 18 16:27:45 PST 2010


On 19/02/10 10:16, Sam Watkins wrote:
> A quick question.  Supposing I want to return an array from my_func(), I can do
> like:
>
> 	...
> 	  return @foo;
> 	}
>
> 	@foo = my_func();
>
> but I normally do it like this because I feel like it should be more efficient:
>
> 	...
> 	  return \@foo;
> 	}
>
> 	$foo = my_func();
>
> This has the unfortunate effect of converting my array to an array ref.  If I
> wanted to reverse that, I think I could use:
>
> 	@foo = @{my_func()};
>
> which is getting ugly and inefficient too.  The same thing happens when
> returning hash variables, except that I suppose it is even more inefficient to
> return it via a list return compared to a reference.
>
> My question is, does perl actually optimize this so it sucks less than I am
> naively supposing it does?  Also, is there any way to make like an alias @foo
> for @$foo, so you can treat an array reference as a normal array without
> writing @$foo all the time?  (and also for hashes)

No, Perl does not optimise it for you, so returning references is 
definitely better for performance.
There isn't any language syntax for the aliasing you're talking about 
either.

> These concerns make me reluctant to use normal perl @array and %hash types at
> all.  If I have to pass and return things by reference, and can't alias these
> back to normal @array and %hash types, I would prefer to use references for
> everything in order to be consistent and avoid having to rewrite code when I
> suddenly need to pass some variable to or from a sub.  This would make the @foo
> %bar syntax useless for anything but the one-liners.  So I'm hoping there is
> some workaround or optimization, and a way to alias them.

Luckily there is. Use the Moose. I think Drew mentioned that in the 
quoted but unrelated text I cut from the bottom of this email. Have you 
investigated Moose yet?

Cheers,
Toby


More information about the Melbourne-pm mailing list