in reply to Is it possible to write a sub that understand default variables ?

Using $_ as the default for a function that normally accepts a list is a bad idea since @a = (); display_thing(@a); would use $_, and that would break the expected behaviour.

However, if you want a function that accepts either zero or one argument, you could do that as follows (pre 5.10):

sub func { my $s = @_ ? $_[0] : $_; ... }

And if you want to arg to be called $_ in your sub:

sub func { for (my $s = @_ ? $_[0] : $_) { ... } }

This last one is particularly ugly. I only use it when the sub consists entirely of s/// statements.

Replies are listed 'Best First'.
Re^2: Is it possible to write a sub that understand default variables ?
by Corion (Patriarch) on Dec 24, 2007 at 17:37 UTC

    I just tried "empty @a" against my solution. The _ prototype forces scalar context on the first argument:

    /opt/perl/bin/perl5.10.0 -M5.10.0 -e 'sub display(_){say $_[0]};@a=(); +display(@a);push@a,"x";display(@a)'

    Whether that is considered to be unintuitive or not depends on the user I guess

      No surprises there
      >perl -le"@a=qw(A B C); print lc @a" 3