Hi Sunita,

On Mon, Jan 3, 2011 at 2:24 PM, Sunita Rani Pradhan
<sunita.prad...@altair.com> wrote:
>            How can I define default arguments in Perl subroutine? Can
> anybody explain with examples?

Sure, the best thing to do is to use named arguments for a subroutine,
by means of using a hash. This is in general better for any subroutine
that uses more than one or two arguments, also because the syntax is
self-explanitory. If you use named arguments you can also use the '||'
operator to assign a value if you don't have one.
For instance, think about a sub like below. If you don't pass the
'status' when adding a user (or if you pass an untrue value), it will
default to 'active'.

=item adduserfoo()

   Adds a user to the foo application.
   adduserfoo(
       email        => 'j...@example.com',
       password   => 'somepass',
       status        => 'active', # default is active, possible
values: active, inactive.
   );

=cut

sub adduserfoo {
   my ($param_ref) = @_;

   my $email = $param_ref->{email};
   my $password = $param_ref->{password};
   my $status = $param_ref->{status} || 'active';

   # do stuff which adds the user
}

--
Mike.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to