in reply to Memory Use and/or efficiency passing scalars to subs

Not related to performance, but rather at ease of use during programming. When I have a subroutine that does something to the values it is passed, I have it run different code paths depending on how the subroutine is called. For example:
sub foo { if (defined wantarray) { # we're in scalar or list context my @param = @_; # make a copy of the parameters foo( @param ); # recursive call for ease of maintenance return @param; # return the result } # we only get here if in void context # do what you need to do on @_ directly, only thing to maintain } #foo
This allows you to use the subroutine in two ways. One directly modifying the parameters passed:
foo( @data );
and one returning the changed parameters, keeping the old:
@newdata = foo( @olddata );
This gives me a lot of flexibility: on the one hand the direct changing which is CPU and memory efficient (no need to copy anything) and the copying way, which also comes in handy if you're passing constant (non left-value) parameters, like so:
@data = foo( qw(foo bar baz) );
If you're really concerned about performance, you could remove the recursive call, but that would leave you with two identical code paths to maintain, which is always a bad thing.

Liz

Replies are listed 'Best First'.
Re: Re: Memory Use and/or efficiency passing scalars to subs
by knexus (Hermit) on Aug 30, 2003 at 21:14 UTC
    Thanks for the tips, I am sure I can make use of them. I need to learn more about "context" in perl. Time to do some reading I suppose.

    Although I am new to Perl, I have coded in ASM, C/C++ for too many years when combined. So, I sometimes get hung up on things when working in a new language trying to relate things to previous experiences, which can be a good or bad thing.

    I appreciate the "ease of use" info becuase I am moving from writing fairly simple scripts to more involved ones and I want them to be easy to maintain and understand.

    Thanks