Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!spool.mu.edu!uunet!zephyr.ens.tek.com!uw-beaver!fluke!gtisqr!roger From: roger@mav.com (Roger Droz) Newsgroups: comp.lang.perl Subject: Re: Subroutine parameters Message-ID: <1991Jun07.161213.22170@mav.com> Date: 7 Jun 91 16:12:13 GMT References: <9105312319.AA21073@no11sun.csd.uwo.ca> Distribution: na Organization: Maverick International Inc. Lines: 88 In article <9105312319.AA21073@no11sun.csd.uwo.ca> clipper@csd.uwo.ca (Khun Yee Fung) writes: > I am using perl to write a program generator. This program has a few > recursive subroutines using more than one array passed among them. > To make sure the subroutines do not alter the content of the arrays, I > use something like: > > @arg1 = @dimen1; > @arg2 = @dimen2; > &traverse($level); > > . > . > . > sub traverse { > local(@dimen1) = @arg1; > local(@dimen2) = @arg2; > local($level) = @_; > > . > . > . > @arg1 = @dimen1; > @arg2 = @dimen2; > &traverse($level); > . > . > } Perl can easily pass arrays by reference. If I were a caller who didn't trust the routine I was calling, I'd make a copy of the array and pass the copy by reference: # Pass @foo and @bar by value. @foo_copy = @foo; @bar_copy = @bar; &traverse($local, *foo_copy, *bar_copy); sub traverse { local($level, *dimen1, *dimen2) = @_; local(@arg1, @arg2); . . . @arg1 = @dimen1; @arg2 = @dimen2; &traverse($level, *arg1, *arg2); . . } Not much improvement because you still have to remember to make copies of the arguments. But after all, it is the caller that's not trusting the called routine to the point of sacrificing performance and passing arrays by value. If you trust the called routine to make its own local copy before it modifies an array, you can: &traverse($level, *foo, *bar); sub traverse { local($level, *arg1, *arg2) = @_; local(@dimen1) = @arg1; local(@dimen2) = @arg2; . . . # work with @dimen1 and @dimen2 . . &traverse($level, *dimen1, *dimen2); . . } I'm posting this instead of mailing it because I'd like to see what the real wizzards have to say on this subject. Personally, I'm greatful for a language where call-by-reference is the rule and call-by-value the exception. (I don't really want to start that religion war. I could be that I just got used to call-by-reference from too much FORTRAN in my impressionable years.) ____________ Roger Droz Domain: roger@mav.COM () () Maverick International UUCP: uw-beaver!gtisqr!roger (_______) Mukilteo, WA ( ) | | Disclaimer: "We're all mavericks here: | | Each of us has our own opinions, (___) and the company has yet different ones!"