Hi Monks,

I'm writing a subroutine which takes a variable number of arguments.  Sometimes the 2nd argument is absent, and for simplicity/conciseness I was hoping to be able to just omit it from the sub call, but it looks as if I might need to explicitly specify '' for that argument.  Is that correct?  Check this code out:

test1('A1',,'A3','A4'); test1('B1','','B3','B4'); sub test1 { print "args=" . join(',',@_) . "\n"; my ($arg1, $arg2) = (shift @_, shift @_); my @argrest = @_; print "arg1=$arg1, arg2=$arg2, argrest=@argrest\n\n"; }
The output is:
args=A1,A3,A4 arg1=A1, arg2=A3, argrest=A4 args=B1,,B3,B4 arg1=B1, arg2=, argrest=B3 B4

As you can see, it looks as if the 2nd argument is completely ignored, unless I explicitly supply it.

Questions:

1. Why does the 3rd argument seem to be seen as the 2nd when the 2nd is omitted? (Please don't say "because the 2nd is omitted").

2. Will I really need to supply the 2nd argument as '' or is there a simple way to get omitted arguments to be recognised?

Thanks.


In reply to Omitted subroutine arguments by tel2

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.