Last Updated: February 25, 2016
·
496
· lepht

Named parameters with default values for subroutines

sub foo {
  my %args = (
    # set your defaults/doc your accepted args here
    arg1 => 'default'
    arg2 => undef,

    # passed-in args replace your defaults
    @_ 
  );

  # also allows for quick checking for missing required args
  for (keys %args) {
    unless ( $args{$_} ) {
      carp("Required argument '$_' was missing from arguments:" . Dumper(\%args));
      return;
    }
  }
}