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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.