To work on $_ by default, check the size of @_. For example,
sub func { local $_ = @_ ? $_[0] : $_; ... } # copy
sub func { local *_ = \(@_ ? $_[0] : $_); ... } # alias
To request a scalar argument, use prototypes. For example,
sub func($) { ... } # scalar
sub func(;$) { ... } # optional scalar
This is required for $str = my_uc my_reverse 'ab', 'cd'; to work.
Finally, use wantarray to determine whether a list or a scalar (or nothing at all) should be returned.
In Perl, your functions would be the following:
sub pp_lcfirst(;$) { local $_ = @_ ? $_[0] : $_; s/(.)/\l$1/; return $_; } sub pp_uc(;$) { local $_ = @_ ? $_[0] : $_; s/(.*)/\U$1/; return $_; } sub pp_reverse { if (wantarray) { my @rv; push(@rv, pop(@_)) while @_; return @rv; } else { my $str = join('', @_); my $rv = ''; my $i = length($str); $rv .= substr($str, $i, 1) while $i--; return $rv; } } sub spaces_to_und(;$) { local $_ = @_ ? $_[0] : $_; s/\s+/_/g; return $_; }
Update: Cleanup.
Update: Fixed the typo japhy noticed in my prototypes.
In reply to Re: subroutine bewilderment: how to mimic builtins
by ikegami
in thread subroutine bewilderment: how to mimic builtins
by dimar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |