in reply to passing subroutine args as a hash: why not?

I, like other responders, like to pass hash *references* as opposed to hashes. This comes in handy especially when you want to pass other things, as well as a hash, as arguments to a subroutine. Hashes and arrays get flattened out into one long string of scalar parameters, so if you stick to passing scalars (like hash references) around, you'll never have problems :-)

Here's a snippet from 'perldoc perlsub':
The Perl model for function call and return values is simple: a +ll func- tions are passed as parameters one single flat list of scalars, + and all functions likewise return to their caller one single flat list +of scalars. Any arrays or hashes in these call and return lists w +ill col- lapse, losing their identities--but you may always use pass-by- +refer- ence instead to avoid this. Both call and return lists may con +tain as many or as few scalar elements as you’d like. (Often a functio +n with- out an explicit return statement is called a subroutine, but th +ere’s really no difference from Perl’s perspective.)
If you instead pass parameters like this:
sub print_person { my $address_hashref = shift; my $hobbies_arrayref = shift; print "address line 1 = $address_hashref->{'addr1'}\n"; print "address line 2 = $address_hashref->{'addr2'}\n"; # etc, etc. # or, turn hashref back into a hash, and arrayref back into an +array my %address = %{$address_hashref}; my @hobbies = @{$hobbies_arrayref}; print "address line 1 = $address{'addr1'}\n"; } my %address = ( "addr1" => "1 Main St", "addr2" => "Suite 101", "city" => "Somecity", "state" => "Somestate" ); my @hobbies = ( "flying", "mountain climbing" ); print_person(\%address, \@hobbies);
HTH.

Replies are listed 'Best First'.
Re: Re: passing subroutine args as a hash: why not?
by Willard B. Trophy (Hermit) on Jun 06, 2003 at 16:02 UTC
    good point, thanks. Complex structures are likely to get alarmingly broken in transit if you just pass 'em as named parameters. Hash refs fix this.

    --
    bowling trophy thieves, die!