I'm in the process of writing a couple of "shortcut" functions, but I'm unsure about implementing the best semantics for the functions. I'm not sure whether the functions should silently take '$_' as an argument when the function is called with zero arguments as seems to be the case with the standard "shortcut" idiom. Using trim from Trim::Text as an example:
sub trim { @_ = @_ ? @_ : $_ if defined wantarray; # disconnect aliases in no +n-void context for (@_ ? @_ : $_) { s/\A\s+//; s/\s+\z// } return wantarray ? @_ : "@_"; }
On the one hand, it allows perlish natural use of the function, such as:
foreach (@args) { <...>; trim; <...>; }
But, on the other hand, empty argument lists may bite you by operating unexpectedly on '$_':
foreach (@args) { my @b; <...> @b = (); trim(@b); # silently the same as trim($_) since @b has no elements <...>; }
I'm honestly tempted to rewrite the "shortcut" function as:
sub trim { if ( !@_ && !defined(wantarray) ) { carp 'Useless use of trim with + no arguments in void return context (did you mean "trim($_)"?)'; ret +urn; } if ( !@_ ) { carp "Useless use of trim with no arguments"; return; + } @_ = @_ if defined wantarray; for (@_) { s/\A\s+//; s/\s+\z// } return wantarray ? @_ : "@_"; }
In the best of all worlds, I'd rewrite the function to differentiate between "trim()" and "trim( () )". But, given the implementation of subroutine argument passing, I haven't come across or originated any way of doing that. (Let me know if you have...)

So, what's the prevailing wisdom on this?

Thanks.

- Wyrd

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.