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

Re: default arguments in subroutine

Thread Previous | Thread Next
From:
Brian Fraser
Date:
January 3, 2011 07:42
Subject:
Re: default arguments in subroutine
Message ID:
AANLkTikU8UVUwFVUjp7qqEbHK20WJ+_KoRqcKgBiULrp@mail.gmail.com
>
>            How can I define default arguments in Perl subroutine? Can
> anybody explain with examples?
>

Sure. But as per usual, there is more than one way to do it. This requires a
Perl 5.10 or newer, for say[0] and the defined-or[1] operator; say can be
replaced with a print and a trailing newline, and any defined-or (//) can be
replaced by a ternary, ala $scalar = defined($scalar) ? $scalar : 'default';

#! /usr/bin/perl
> use strict;
> use warnings;
> use 5.010;
>
> sub marine {
>     no warnings 'uninitialized'; #Only to stop warnings in the upcoming
> join; Not for production code! Usually!
>     my ($first, $second) = @_;
>     say "marine called with arguments [", join('][', @_ ), "]";
>     $first      //= q{I'm the first default argument!};
>     $second //= q{I'm the second default argument!};
>
>     say "[$first]";
>     say "[$second]\n";
> }
>
> marine();
> marine('Hello');
> marine('Hello', undef);
> marine(undef, 'Goodbye');
> marine('Hello', 'Goodbye');
>
> That example shoudln't be too hard to follow; We assign the first two
elements of @_ to $first and $second, check if they are defiend, and if they
aren't, assign the defaults.

>
> sub aquatic {
>     no warnings 'uninitialized';
>     say "aquatic called with arguments [", join('][', @_ ), "]";
>     $_[0] //= q{I'm the first default argument!};
>     $_[1] //= q{I'm the second default argument!};
>
>     say "[$_[0]]";
>     say "[$_[1]]\n";
> }
>
> aquatic();
> aquatic('Hello');
> aquatic('Hello', undef);
> aquatic(undef, 'Goodbye');
> aquatic('Hello', 'Goodbye');
>
> This one manipulates @_ [2] directly, but is pretty much the saem as before


> {
> use signatures;
>
> sub idea ($first, $second) {
>     no warnings 'uninitialized';
>     say "idea called with arguments [", join('][', @_ ), "]";
>     $first      //= q{I'm the first default argument!};
>     $second //= q{I'm the second default argument!};
>
>     say "[$first]";
>     say "[$second]\n";
> }
>
> idea();
> idea('Hello');
> idea('Hello', undef);
> idea(undef, 'Goodbye');
> idea('Hello', 'Goodbye');
>
> }
>
This one is the mandatory CPAN solution; It makes use of the signatures[3]
module, which should be a pain to install on Windows.

Brian.

[0] http://perldoc.perl.org/functions/say.html
[1] http://perldoc.perl.org/perlop.html#C-style-Logical-Defined-Or
[2] http://perldoc.perl.org/perlsub.html
[3] http://search.cpan.org/~flora/signatures-0.06/lib/signatures.pm<http://search.cpan.org/%7Eflora/signatures-0.06/lib/signatures.pm>


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