in reply to Global vars?
Why do you think a subroutine making local copies of parameters coming in is a bad thing? You could do as Roger suggested and pass the variables by reference, but then the code to set those "reference" variables becomes somewhat harder to understand - especially for newbies.
If your concern is taking up too much memory for creating unnecessary variables, then - I could be wrong about this, but here is my thought - creating local variables in a subroutine will take more memory, but as soon as those variables go out of scope (at the end of the subroutine), that memory is then made available again. So I think(?) that only causes a slight increase in memory usage, and I believe it's only for the scope of the subroutine.
My preference is to keep the code as simple and understandable as possible - for everyone, including newbies. And, as you already said, it makes the code more self documenting - I prefer to do just as you did:
sub do_something { my $a = shift; # assign 1st arg to $a my $b = shift; # assign 2nd arg to $b my $c = shift; # assign 3rd arg to $c ### now do something with $a, $b, $c return ($a, $b, $c); } my $x = 1; my $y = 2; my $z = 3; my ($x, $y, $z) = do_something($x, $y, $z); Having a subroutine 1. take parameters in, and assign to local variables 2. process the local variables 3. return what needs to be returned
keeps the code modular, and fully encapsulates the functionality within the subroutine, so that all the caller needs to do is know the api for what to give it, and what it will give back. And the calling code is kept clean and simple and self-documenting as well - you know not only what you're giving it, but also what you're getting back.
If you instead use the pass-by-reference approach, then in order to understand the calling code, you also need to understand the subroutine code since the calling code is no longer self explanatory. IMHO, pass-by-reference is fine, but makes the code more complex (not as easy to understand).
|
|---|