Bonjour Monks,

I have an optimization/minimum typing question. I wonder what the best and/or shortest method is for assigning default values to variables. For example, a typical subroutine call for me looks like:

use vars qw($VAR2); # global defaults and whatnot $VAR2 = 'thingamabob'; sub routine { my $input_ref = {@_}; my $var1 = $input_ref->{var1} || ''; my $var2 = $input_ref->{var2} || $VAR2; ...etc... }

This seems to work fairly well for me, however, it doesn't allow me create subroutine boolean flag called "do_this" that defaults to true, but the user can explicitly set false, eg:

sub routine { my $input_ref = {@_}; my $do_this = $input_ref->{do_this} || 1; }

If the user calles routine( do_this => 0 ), do_this will, obviously still be true. Now, I know how to code around this with:

my $do_this = 0; if ($input_ref->{do_this} eq '0') { $do_this = 0 } else { $do_this = 1 };

But that seems a little long winded. I was wondering if the Monks had any input (ha!) on this, or if my whole default assignment strategy is misguided.

Thanks,
Justin


In reply to Best method of assigning "default" values? by jqcoffey

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.