in reply to subroutine bewilderment: how to mimic builtins
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: subroutine bewilderment: how to mimic builtins
by japhy (Canon) on Feb 07, 2006 at 23:59 UTC | |
Re^2: subroutine bewilderment: how to mimic builtins
by ysth (Canon) on Feb 08, 2006 at 02:43 UTC | |
by ikegami (Patriarch) on Feb 08, 2006 at 03:55 UTC | |
by ysth (Canon) on Feb 08, 2006 at 04:39 UTC |