in reply to Return a Reference or Array?

Have you ever thought about returning neither but something else instead?

I could imagine that you do pretty much the same things with all the arrays you return from your various subs (checking their sizes, iterating over them etc).

So why not wrap your arrays in an object that provides nice convenience methods, iterators etc do make life easy for the client code?

In that way you ALWAYS return the same entity (an object - contextual returns are nice but can be confusing to some people) regardless of the list-size (with the memory consumtion of a returned reference), so no special cases and you could build an interface like this:

my $ret = &my_sub(@args); # returns an object that wraps a list if(! $ret->isEmtpy ) { $ret->each( sub { print $_ } ); }

Just an idea...

Replies are listed 'Best First'.
Re^2: Return a Reference or Array?
by moritz (Cardinal) on Apr 06, 2009 at 22:07 UTC
    If the array actually represents a vector or matrix, then there's already a good library for it: PDL.

    If not, chances are that there's already a good library for it on CPAN anyway ;-)

    my $ret = &my_sub(@args);

    In general there's no need to add the & in front of sub calls. On the contrary it has some effects that aren't desirable most of the time, like disabling prototype checking.

      And I thought prototype checking was undesirable :-)

      I just added the "&" for clarity - and I sometimes use it myself in some one-off hacks where I call a sub before I define it (just to keep the parser happy).

      Apart from prototype checking what else are the differences between

      &foo(@args);
      and
      foo(@args);
      ?
        From the docs (perldoc perlsub):
        If a subroutine is called using the & form, the argument list is optional, and if omitted, no @_ array is set up for the subroutine: the @_ array at the time of the call is visible to subroutine instead. This is an efficiency mechanism that new users may wish to avoid.

        CountZero

        A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James