pijush has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!!

How can I pass optional parameters in a function? Here is my code.

print "Testing optional parametrs\n"; prog( 1,,,2,3); print "End\n"; sub prog { my($a,$b,$c,$d,$e) = @_ ; print "a = $a\n"; print "b = $b\n"; print "c = $c\n"; print "d = $d\n"; print "e = $e\n"; }
In the above programme I want to keep two parameters optional, i.e., if user does not want to pass 2nd and 3rd parameter, then he/she simply call it like prog(1,,,2,3). But when I am trying to use like this the program output is a=1 b=2 c=3 d= e= , but my desired output is a=1 b= c= d=2 e=3. I know that if I call the prog function as prog(1,"","",3,4), I can get the desired output, but for optional parameter I have to put "", which is not desirable. Can anyone please tell me how I can get the fucntionality?

Thanks in advance.
-Pijush

Replies are listed 'Best First'.
Re: Optional parameter passing to a function??
by davorg (Chancellor) on Aug 03, 2004 at 12:35 UTC

    You would need to pass undef in the missing slots.

    prog(1,undef,undef,2,3);

    But if you have optional parameters you'll be far better off passing named parameters using a hash.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Optional parameter passing to a function??
by ccn (Vicar) on Aug 03, 2004 at 12:33 UTC

    You can pass a hash as parameters list:

    sub prog { my %args = ( a => 'default_a', b => 'default_b', c => 'default_c', d => 'default_d', @_ ); print "a => $args{a}\n"; print "b => $args{b}\n"; print "c => $args{c}\n"; print "d => $args{d}\n"; } prog( b => 1, a => 2);
Re: Optional parameter passing to a function??
by sweetblood (Prior) on Aug 03, 2004 at 12:40 UTC
    I have written several subs that have optional parameters but have always put the at the end.
    <pseudo-code>
    sub foo { my ($p1, $p2, $p3, $p4, p5) = @_; do { #something } if $p4; do { #something } if $p5; #etc }
    </pseudo-code>
    Then you can call your sub with 3,4,5 (or any number) of parameters

    or

    you can call your sub like:

    prog(1,"","",2,3)
    or

    prog(1,undef,undef,2,3)
    HTH

    Sweetblood

Re: Optional parameter passing to a function??
by ysth (Canon) on Aug 03, 2004 at 19:38 UTC
    The term for using a hash or pairlist that people have shown is "named parameters". Try searching here for many of the previous discussions and modules that help.

    (In the perl core, CGI is a not-for-the-faint-of-heart example of a bastardized positional/named parameter scheme.)