On Monday 03 Jan 2011 17:51:08 Michiel Beijen wrote:
> 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
> }
> 

Your subroutine implementation and the example do not match. Either add {...} 
around the subroutine parameters to make it an anonymous hash reference, or 
(less preferably IMHO) convert $param_ref to my %params = @_ (and omit the 
->).

Regards,

        Shlomi Fish

> --
> Mike.

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
Escape from GNU Autohell - http://www.shlomifish.org/open-
source/anti/autohell/

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/


Reply via email to