Sub::ArgShortcut - simplify writing functions that use default arguments
use Sub::ArgShortcut::Attr;
sub mychomp : ArgShortcut { chomp @_ }
while ( <> ) {
# make a chomped copy of $_ without modifying it
my $chomped_line = mychomp;
# or, modify $_ in place
mychomp;
# ...
}
This module encapsulates the logic required for functions that assume $_
as their argument when called with an empty argument list, and which modify their arguments in void context but return modified copies in any other context. You only need to write code which modifies the elements of @_
in-place.
This function takes a code reference as input, wraps a function around it and returns a reference to that function. The code that is passed in should modify the values in @_
in whatever fashion desired. The function from the synopsis could therefore also be written like this:
use Sub::ArgShortcut;
my $mychomp = argshortcut { chomp @_ };
Instead of using argshortcut to wrap a code reference, you can write regular subs and then add Sub::ArgShortcut functionality to them implicitly. Simply use Sub::Shortcut::Attr
instead of Sub::Shortcut, then request its behaviour using the :ArgShortcut
attribute on functions:
sub mychomp : ArgShortcut { chomp @_ }
my $mychomp = sub : ArgShortcut { chomp @_ };
Sub::ArgShortcut exports argshortcut
by default.
Passing an empty array to a shortcutting function will probably surprise you: assuming foo
is a function with :ArgShortcut
and @bar
is an empty array, then calling foo( @bar )
will cause foo
to operate on $_
! This is because foo
has no way of distinguishing whether it was called without any arguments or called with arguments that evaluate to an empty list.