walkingthecow has asked for the wisdom of the Perl Monks concerning the following question:

I have a subroutine that has two parameters: username and password. I would like to setup that subroutine so that it accepts both methods of parameters, meaning foo(user=>$user, pass=>$pass) AND it could also accept foo($user,$pass)... Here is what I have (it accepts user=> and pass=> args:

sub ssh_connect { my ($self,%args) = @_; my $user = $args{user}; my $pass = $args{pass}; print "$user and $pass\n"; }

Replies are listed 'Best First'.
Re: Simple Subroutine Question
by tilly (Archbishop) on Aug 01, 2009 at 00:53 UTC
    I would strongly recommend only accepting one form. If you want to accept both, have 2 different functions. That way if you ever want to add a third argument or fourth argument (such as, oh, a machine to connect to, a port, options for an SSH tunnel, etc) you'll be in good shape.

    If you disregard said advice, you could do it as follows:

    sub ssh_connect { my ($self, $user, $pass) = @_; if (3 < @_) { (undef, my %args) = @_; $user = $args{user} or confess("No user"); $pass = $args{pass} or confess("No pass"); } print "$user and $pass\n"; }
    Alternately you could make the two forms be
    $foo->ssh_connect($user, $password); $foo->ssh_connect({user => $user, pass => $password});
    and dispatch on whether there are fewer than 3 arguments. This is actually a saner way to go, but it does require {}.
      If choosing between the two, what do the PerlMonks suggest is a better way of doing this? I'd like it to be EASY to write and EASY to read... So, I was thinking the user=> would be good, but there are MANY functions in this bad boy and not sure if I should have them all use that method...

      An example of a lot of arguments is below:
      foo->adduser(id=>$id, uid=>$uid, prgrp=>$pgrp, sgrps=>$sgrps, gcos=>$gcos, expire=>$expire)... I mean, is that ridiculous??
Re: Simple Subroutine Question
by AnomalousMonk (Archbishop) on Aug 01, 2009 at 02:13 UTC