From: [EMAIL PROTECTED]
> 
> This is going to be a head-slapper, I know, but it's late and 
> my brain hurts... I've got a script that has a sub that 
> accepts a hash of arguments, one of which happens to be an 
> array. If I pass the array as a reference, everything works fine. 
> 
> Now for the head slapping part, how do I handle things INSIDE 
> the sub so I don't have to pass the array as a reference?  
> Code and desired output are below. 
> 
> Thanks, 
> 
> Deane 
> 
> use strict; 
> use warnings; 
> 
> sub do_smthng{ 
> my %args = ( -s1 => undef, 
>              -s2 => undef, 
>              -ar => undef, 
>              @_ 
>            ); 
> 
>    print "    s1: $args{-s1}\n"; 
>    print "    s2: $args{-s2}\n"; 
>    print "ary[0]: $args{-ar}->[0]\n"; 
>    print "ary[1]: $args{-ar}->[1]\n"; 
>    print "ary[2]: $args{-ar}->[2]\n"; 
> } 
> 
> 
> my @arg_ary = ( 'alpha', 'bravo', 'charlie' ); 
> 
> do_smthng( -s1 => 42, 
>            -s2 => 96, 
>            -ar => [EMAIL PROTECTED] ); # I wanna lose the "\" here 
> 
> 
> Desired output: 
>     s1: 42 
>     s2: 96 
> ary[0]: alpha 
> ary[1]: bravo 
> ary[2]: charlie

I think you're out of luck here.  The array is part of a hash and the
only way to stick an array inside a hash is to use a reference.

One thing you could do is to design the sub so that it uses the '-ar'
as a marker to indicate that the rest of the input is an array.  The
result is that you are not sending a pure hash to the subroutine and
so you must separate it yourself.

It would look something like this:

    sub do_smthng{
        my %args;
        # Read in hash argument pairs
        while ($_[0] ne '-ar') {
            my $var = shift;
            $args{$var} = shift;
        }
        # Read in the array
        if ($_[0] eq '-ar') {
            shift; # Junk the '-ar' array element
            $args{-ar} = [ @_ ];
        }

        print "    s1: $args{-s1}\n"; 
        print "    s2: $args{-s2}\n"; 
        print "ary[0]: $args{-ar}->[0]\n"; 
        print "ary[1]: $args{-ar}->[1]\n"; 
        print "ary[2]: $args{-ar}->[2]\n"; 
    }
    
    @arg_ary = qw( alpha bravo charlie );

    do_smthng( -s1 => 42,
               -s2 => 96,
               -ar => @arg_ary );

Notice that @_ in this case will look like this:
@_ = ( '-s1', 42, '-s2', 96, '-ar', 'alpha', 'bravo', 'charlie' );

The '-ar' and the array must be the last arguments to the subroutine.
Also, as written, the '-ar' must be lowercase.

Bowie
_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to