> -----Original Message-----
> From: Robert Thompson [mailto:[EMAIL PROTECTED]]
> Sent: Tuesday, June 04, 2002 3:38 PM
> To: [EMAIL PROTECTED]
> Subject: Passing array to subroutine problem
> 
> 
> Hello,
> 
>       I have a subroutine where I want to pass some 
> paramaters to it, but assign default ones if a paramater is 
> not passed. This is similar to CGI.
> 
>   &mySub( -param1=>'my value', -param3=>'value' );    # 
> -param2 would get a default value
> 
> 
>       The problem I am running into is if one of the 
> paramaters passed is an array, and the value passed is 0, the 
> default value gets assigned instead of the 0 that was passed. 
> Below is some code that shows what I am doing and how it breaks:
> 
> #!/usr/bin/perl -Tw
> 
> use strict;
> 
> &Baz( one=>'all good', two=>['zero','one'] ); # text works
> &Baz( one=>'bad', two=>[0,1] );                       # numbers fail
> &Baz( one=>'more bad', two=>['0','1'] );      # quoted numbers fail
> 
> 
> sub Baz {    
>   my %params = @_;
> 
>   $params{one}    = "default" unless $params{one};
>   $params{two}[0] = "default" unless $params{two}[0];

Comment this one out.

>   $params{two}[1] = "default" unless $params{two}[1];
> 
>   # let's try some more, they still fail...
>   $params{two}[0] = "default" unless defined($params{two}[0]);

This one works, but you need to comment out the one 3 lines up.

>   $params{two}[0] = "default" unless $params{two}[0] || 
> $params{two}[0] == 0;
> 
>   print "one    is $params{one}\n";
>   print "two[0] is $params{two}[0]\n";
>   print "two[1] is $params{two}[1]\n";
>   print "\n";
> 
>   return(1);
> }
> __END__

If you want to have default values for arguments, you can use
the following trick:

sub foo
{
    my %args = (arg1 => 'default1', arg2 => 'default2', @_);
    ...
}

The trick is to put your defaults first in the list, followed by @_. If
the same key appears more than once in a list assignment to a hash, only
the last value is used.

Now if you call foo(arg1 => 'bar'), the 'bar' will override 'default1'.
If you just call foo(), $args{arg1} will be 'default1'.

Make sense?

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

Reply via email to