Hi Sunita, On Monday 03 Jan 2011 15:24:54 Sunita Rani Pradhan wrote: > Hi All > > > > How can I define default arguments in Perl subroutine? Can > anybody explain with examples? >
One option is to extract each arguments one by one and assign default values to them using "||": sub greet_person { my $first_name = shift || "Sunita"; my $last_name = shift || "Pradhan"; my $greeting = shift || "Hello"; print "$greeting $first_name $last_name!\n"; } Note that this will not handle "0" passing properly. For that you need to test for definedness using the perl-5.10.x-or-above // operator or explicitly. You can also do it using named arguments: sub greet_person { my ($args) = @_; my $first_name = $args->{first_name} || "Sunita"; . . . } And naturally you can do: sub greet_person { my ($first_name, $last_name, $greeting) = @_; $first_name ||= "Sunita"; $greeting ||= "Hi"; } There may be modules on CPAN to facilitate all that. Regards, Shlomi Fish -- ----------------------------------------------------------------- Shlomi Fish http://www.shlomifish.org/ "The Human Hacking Field Guide" - http://shlom.in/hhfg Chuck Norris can make the statement "This statement is false" a true one. Please reply to list if it's a mailing list post - http://shlom.in/reply . -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/