How to code an implicit $_ argument?
- From: tmcd@xxxxxxxxx (Tim McDaniel)
- Date: Wed, 19 Aug 2009 00:10:23 +0000 (UTC)
This is a function which trims leading and trailing whitespace from a
variable in-place, operating on $_ if there are no arguments provided.
(If the value is undef, it leaves it undef.) I feel a bit unclean
using "goto &sub" and hand-manipulation of @_. Opinions? Better ways
to do it?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#! /usr/bin/perl -w
use strict;
sub trim(;\$) {
if (@_ == 0) {
$_[0] = \$_;
goto &trim;
}
my $var = $_[0];
if (defined $$var) {
$$var =~ s/^\s+//;
$$var =~ s/\s+$//;
}
return $$var;
}
my $v = ' abc ';
trim $v;
if ($v ne 'abc') {
warn "\$v should be 'abc' but is '$v' instead.\n";
}
$_ = ' 123 ';
trim;
if ($_ ne '123') {
warn "\$_ should be '123' but is '$_' instead.\n";
}
exit 0;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The only clean way I see to do it is this, but I don't know whether
later Perl interpreters notice and optimize the tail recursion.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
....
sub trim(;\$);
sub trim(;\$) {
if (@_ == 0) {
return trim($_);
}
my $var = $_[0];
if (defined $$var) {
$$var =~ s/^\s+//;
$$var =~ s/\s+$//;
}
return $$var;
}
....
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a recent message, someone mentioned that Perl 5.10 has the _
prototype character: if there is no matching argument, use $_.
But that doesn't work here, as the following code produces
Can't use string (" abc ") as a SCALAR ref while "strict refs"
in use at /home/tmcdaniel/local/test/084.pl line 7.
and "sub trim(\_)" causes
Malformed prototype for main::trim: \_ at
/home/tmcdaniel/local/test/084.pl line 15.
Also, where is _ documented? I don't see it in "man perlsub" for Perl
5.10 in Cygwin.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
....
sub trim(_) {
my $var = $_[0];
if (defined $$var) {
$$var =~ s/^\s+//;
$$var =~ s/\s+$//;
}
return $$var;
}
....
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
Tim McDaniel, tmcd@xxxxxxxxx
.
- Follow-Ups:
- Re: How to code an implicit $_ argument?
- From: Ben Morrow
- Re: How to code an implicit $_ argument?
- From: Willem
- Re: How to code an implicit $_ argument?
- From: Ilya Zakharevich
- Re: How to code an implicit $_ argument?
- From: John W. Krahn
- Re: How to code an implicit $_ argument?
- Prev by Date: undef($foo) versus $foo = undef()?
- Next by Date: Re: How to code an implicit $_ argument?
- Previous by thread: undef($foo) versus $foo = undef()?
- Next by thread: Re: How to code an implicit $_ argument?
- Index(es):
Relevant Pages
|