develooper Front page | perl.beginners | Postings from January 2011

Re: default arguments in subroutine

Thread Previous | Thread Next
From:
Michiel Beijen
Date:
January 3, 2011 07:51
Subject:
Re: default arguments in subroutine
Message ID:
AANLkTim3kj91kHY3VUHnGhmvrBsU08wV9Mq9N+7Znrjj@mail.gmail.com
Hi Sunita,

On Mon, Jan 3, 2011 at 2:24 PM, Sunita Rani Pradhan
<Sunita.Pradhan@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        => 'joe@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.

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About