Last active
December 11, 2015 13:58
-
-
Save lepht/4611203 to your computer and use it in GitHub Desktop.
Perl named, self-documenting subroutine arguments with default values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Perl named, self-documenting subroutine arguments with default values | |
sub foo { | |
my %args = ( | |
# Set your defaults/doc your accepted args here | |
arg1 => 'default' | |
arg2 => undef, | |
somelist => [qw( some stuff )], | |
@_ # Passed-in args replace your defaults | |
); | |
# Do stuff... | |
} | |
# When calling your subroutine, just pass in the arguments as documented in the defaults. | |
# Any keys not specified will retain their default value: | |
foo( arg2 => 'bar', somelist => ['baz'] ); | |
# Results in: | |
%args = ( | |
'arg2' => 'bar', | |
'arg1' => 'default', | |
'somelist' => ['baz'] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment