in reply to Is silent use of $_ for empty argument lists reasonable for "shortcut" functions?

I may be missing some subtleties here, but if you want a no-arg call to operate on $_ (handy shortcut) and you don't want a call with an empty array arg to operation on $_ by mistake (nasty unexpected side-effect), the way to write the sub would (I think) be like this:
sub trim { my @args = ( @_ ) ? @_ : $_; for ( @args ) { s/\A\s+//; s/\s+\z//; } return wantarray ? @args : $args[0]; }
If you pass an empty array to that verion, it will not modify $_.

Update -- test suite:

#!/usr/bin/perl use strict; sub trim { my @args = ( @_ ) ? @_ : $_; for ( @args ) { s/\A\s+//; s/\s+\z//; } return wantarray ? @args : $args[0]; } $_ = " test "; print "test 1: ==" . trim . "==$_==\n"; $_ = " 1234 "; my @b = (); trim( @b ); print "test 2: ==". $_ . "==@b==\n"; my @c = ( " a ", " b ", " c " ); my $d = join "", trim( @c ); print "test 3: ==". $_ . "==" . $d . "==@c==\n"; __OUTPUT__ test 1: ==test== test == test 2: == 1234 ==== test 3: == 1234 ==abc== a b c ==

Having updated "test 1" to print out both the return value of trim and $_, I see that $_ is never modified, which I gather is not what you want. Sorry -- I get your point now, and I don't have an answer.

Replies are listed 'Best First'.
Re^2: Is silent use of $_ for empty argument lists reasonable for "shortcut" functions?
by ikegami (Patriarch) on Aug 27, 2007 at 17:15 UTC

    Test 1 is fine. $_ shouldn't be modified in that case. (Not void context.)

    Test 2 is the one that fails. It doesn't print == 1234  ==1234== as it should.