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

I would probably do something like:

#!/usr/bin/env perl

use strict;
use warnings;

sub foo
{
    my $bar = shift || 'default bar';
    my $baz = shift || 'default baz';

    print "\$bar=$bar\n";
    print "\$baz=$baz\n";
}

foo;
foo 'bar';
foo qw/bar baz/;

__END__

If you wanted something like named arguments, where you could specify
arguments in any order, then I'd use a hash reference instead.

#!/usr/bin/env perl

use strict;
use warnings;

# There might be a one liner to do this, but I couldn't get it
# working with hash references. :P
sub augment
{
    my $first = shift;
    my $second = shift;

    die "Invalid argument"
            unless ref $first eq 'HASH' && ref $second eq 'HASH';

    for my $key (keys %$second)
    {
        $first->{$key} = $second->{$key} unless exists $first->{$key};
    }
}

sub foo
{
    my $args = shift || {};
    my %defaults = (
        bar => 'default bar',
        baz => 'default baz'
    );

    die "Invalid argument" unless ref $args eq 'HASH';

    # Use values in %defaults for missing values in %$args.
    augment $args, \%defaults;

    print "\$args->{bar}=$args->{bar}\n";
    print "\$args->{baz}=$args->{baz}\n";
}

foo;
foo { bar => 'bar' };
foo { baz => 'baz' };
foo { bar => 'bar', baz => 'baz' };
foo { baz => 'baz', bar => 'bar' };

__END__

If you're new to Perl then there are many topics that you'll need to
read up on. For operators, like ||, q//, and qw//, read `perldoc
perlop`. For references, try `perldoc perlref`. For passing arguments
to subroutines, try `perldoc perlsub`. For built-in subroutines that
you don't know about, try `perldoc -f name`. For example, `perldoc -f
shift` and `perldoc -f ref`.


-- 
Brandon McCaig <www.bamccaig.com> <bamcc...@gmail.com>
V zrna gur orfg jvgu jung V fnl. Vg qbrfa'g nyjnlf fbhaq gung jnl.
Castopulence Software <http://www.castopulence.org/> <bamcc...@castopulence.org>

--
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