Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Default subroutine parameters

by perlplexer (Hermit)
on Apr 22, 2002 at 16:41 UTC ( [id://161092]=note: print w/replies, xml ) Need Help??


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';
    }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://161092]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-03-29 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found