Greetings monks:
I have an object which is designed to have default values for parameters if they are not supplied. I am currently using the following style, but I can't help but feel that my solution is not very "Perl-like".
#!usr/bin/perl -w use strict; #Demonstrate and test usage my $test = Test::new(); $test->defaults(); $test->defaults(0); $test->defaults(0, 0); $test->defaults(0, 0, 0); package Test; sub new { my $self = {}; bless($self); return $self; } #This is the pertinent part... sub defaults { my ($self, $default1, $default2, $default3) = @_; $default1 = 1 if($#_ < 1); #Is there a better way to do this? $default2 = 2 if($#_ < 2); $default3 = 3 if($#_ < 3); print("$default1 $default2 $default3\n"); } 1;
EDIT Well, as I say in reply to AR I only have version 5.8.8 available on the workstation where this runs. As an interesting aside, my Debian Stable server has 5.10.0. :) Anyway, I guess what I'm doing isn't so bad.
EDIT 2 I should probably clarify further: I don't really intend to have long parameter lists. If I did, I would use mapped parameters. Or better yet I would find a way to not do that in the first place. My problem is that I'm having a difficult time finding a nice way to tell the difference between the user sending two parameters, the last of which is 0, and the user sending one parameter wanting me to use the default second parameter (which is typically 1 for "Yes"). There is one place that I found where the code I'm modifying takes two parameters, and the second one has reasonable default. It's particularly irksome if the first parameter ("self" notwithstanding) is 0, because then I wind up mucking up the whole works.
In reply to Correct idiom for default parameters by mrider
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |