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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|