in reply to Default subroutine parameters

Perhaps this may be of some use
sub foo{ my $bar = defined $_[0] ? $_[0] : 'default'; # ... }
--perlplexer

Replies are listed 'Best First'.
Re:x2 Default subroutine parameters
by grinder (Bishop) on Apr 23, 2002 at 07:16 UTC
    Or, keeping in the spirit of this lightweight approach, i.e. not bringing a hash to bear on the problem, if you want to munch @_ with shift you will have to do something like:
    #! /usr/bin/perl -w use strict; sub x { # my $one = do { @_ ? shift : 'default' }; # my $two = do { @_ ? shift : 43 }; my $one = do { my $arg = shift; defined($arg) ? $arg : 'default' } +; my $two = do { my $arg = shift; defined($arg) ? $arg : 43 }; print "x($one, $two)\n"; } x(); x( 'this' ); x( 1, 2 );

    update: sheesh, misread a requirements document and get downvoted into oblivion. I corrected the code; you can stop now. The principal idea I wanted to show was that a do block is a pretty nice way of doing this, because the default value appears at the end of the code, making it easy to spot, thus letting you gloss over the mechanics.


    print@_{sort keys %_},$/if%_=split//,'= & *a?b:e\f/h^h!j+n,o@o;r$s-t%t#u'
      Your method doesn't take into account the fact that @_ may contain one or more undef elements.
Re^2: Default subroutine parameters
by Anonymous Monk on Dec 16, 2008 at 08:23 UTC
    sub foo { my ($bar)=@_;
    $bar ||= 'default';
    }