Once of the first modules I wrote did some simple manipulations with dates (this was in early 1999, before I knew what CPAN was all about). Since it does what I want and I know how it works, I pulled it off of a dusty shelf and cleaned up the code so I could re-use it for a project. The work I did included changing one subroutine call from
to use a hash for passing the parameters. Originally, if I wanted to call using only some of the parameters, I'd have to sayAdjust ( $Date, $DeltaYears, $DeltaMonths, $DeltaDays );
Now I pass in an anonymous hash reference so that those examples become:Adjust ( $Date, 0, 0, 15 ); # or Adjust ( $Date, 0, -1, 0 ); # or Adjust ( $Date, -3, 0, -1 );
The great thing about this technique is that I only pass in the values I need to. If the values aren't there, the subroutine will assume some default value. How?Adjust ( { date => $Date, day => 15 } ); # or Adjust ( { date => $Date, month => -1 } ); # or Adjust ( { date => $Date, year => -3, day => -1 } );
The double bar zero at the end of the three lines allows an undefined value to be interpreted as a zero -- this allows you to specify whatever default value you want, 5, 42, "U.S." or whatever.sub Adjust { my ( $Args ) = @_; my $Year = $Args->{ year } || 0; my $Month = $Args->{ month } || 0; my $Day = $Args->{ day } || 0; # More code .. }
Obviously, this becomes much cooler the more parameters you pass in -- and another great thing is that you can expand the subroutine's functionality without worrying about how it affects old code. In an old script I wrote, I had a subroutine that accepted a dozen or so parameters; adding a new one meant searching through the other scripts that called that script and updating all of them.
This technique is much easier to maintain; in my example, I would have had to set up a default value for the new parameter -- and I'd be done!
--t. alex
"Excellent. Release the hounds." -- Monty Burns.
In reply to Re: Trying to learn about References
by talexb
in thread Trying to learn about References
by dru145
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |