on Fri, 09 Aug 2002 09:11:24 GMT, [EMAIL PROTECTED] (John W. Krahn) 
wrote:

> sub mysub {
>   my $a = shift;
>   my $b = shift || 5;
> }

This only works when 0 or '' are not allowed for the second 
parameter.
   
   my $a = $_[0];
   my $b = defined($_[1]) ? $_[1] : 5;

takes care of this.

An elegant solution, especially when you have a lot of possible 
parameters, is to use named parameters:

    #! /usr/bin/perl -w
    use strict;
    use Carp;

    mysub (A => 10, C => 'Hello, world');

    sub mysub {

       croak "Invalid parameter list" if @_ % 2;
       my %defaults = (
              A => 1,
              B => 2,
              C => 'A string');
      
       my %parameters = (%defaults, @_);
   
       for my $p (sort keys %parameters) {
           print "$p has value '$parameters{$p}'\n";
       }
       return;
    }


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to