in reply to Builtin functions defaulting to $_
How to make your own function that defaults to $_:
sub myfunc { my $arg = @_ ? $_[0] : $_; for ($arg) { ... } }
The for is a convenient way to alias $_. (local $_ is buggy. It doesn't work well if $_ is tied or aliased to someting that's tied, and it doesn't protect pos($_).) Of course, you could just work with $arg directly instead of aliasing $_ to it.
The use of a lexical ($arg) allows us to modify $_ without affecting the argument in the caller. If you don't modify $_, the above can be simplified to
sub myfunc { for (@_ ? $_[0] : $_) { ... } }
|
|---|