perl - How to pass optional arguments to a function -
i'm trying make function module accept optional arguments in form of:
function(arg1, optional1 => opt1, optional2 => opt2, ..);
yet can't find anywhere shows explanation how this. came following solution accept email
, alpha
, html
arguments, it's extremely convoluted , can't believe there isn't shorter way accomplish this:
sub test { ($s, @args) = @_; $alpha = 1; $html = 0; $email = 0; for(my $i = 0; $i < scalar(@args); $i++) { if($args[$i] eq "alpha") { $i++; $alpha = $args[$i]; } elsif($args[$i] eq "email") { $i++; $email = $args[$i]; } elsif($args[$i] eq "html") { $i++; $html = $args[$i]; } } return ($alpha, $email, $html); } ($a, $b, $c) = test("stuff", ndhgffs => 1, email => 1, alpha => 0); print $a . $b . $c;
edit:
thanks answer below , comments below that, solved it:
sub test { ($s, %opts) = @_; $email = $opts{'email'} // 0; $alpha = $opts{'alpha'} // 1; $html = $opts{'html'} // 0; return ($alpha, $email, $html); }
sub function { $arg1 = shift; $arg2 = shift; %opts = @_; $optional1 = delete($opts{$optional1}); $optional2 = delete($opts{$optional2}); croak("unrecognized parameters ".join(' ', keys(%opts))) if %opts; ... }
or
sub function { ($arg1, $arg2, %opts) = @_; $optional1 = delete($opts{$optional1}); $optional2 = delete($opts{$optional2}); croak("unrecognized parameters ".join(' ', keys(%opts))) if %opts; ... }
notes:
if don't want bother checking unrecognized options, don't need
delete
.you can assign default values when argument omitted or undef using
my $arg = delete($opts{$arg}) // 'default'; # perl 5.10+
Comments
Post a Comment