C_T has asked for the wisdom of the Perl Monks concerning the following question:

I'm trying to modify/populate a hash in a subroutine, and I want to avoid using global variables since the sub may be in a separate module. Although the following code works, I KNOW there's a more elegant way to do this. Can anyone help? Thanks!
$hash_ref = modifyHash(\%my_hash); %my_hash = %{$hash_ref}; # hash is now modified sub modifyHash() { my $hash_ref = shift; my %sub_hash = %{$hash_ref}; # Do something to the hash $sub_hash{'test'}=1; return (\%sub_hash); }
Charles Thomas
Madison, WI

Replies are listed 'Best First'.
Re: Modifying a hash in a subroutine?
by ikegami (Patriarch) on Aug 19, 2004 at 21:18 UTC

    The code simplifies to:

    modifyHash(\%my_hash); sub modifyHash { my $hash_ref = shift; # Do something to the hash ${$hash_ref}{'test'} = 1; #$hash_ref->{'test'} = 1; #alternative }

    basically, use {$hash_ref} wherever my_hash would have appeared:

    %my_hash -> %{$hash_ref} keys(%my_hash) -> keys(%{$hash_ref}) %my_hash = (); -> %{$hash_ref} = () $my_hash{$key} -> ${$hash_ref}{$key}
      Thanks!

      You guys rock!

      CT

      Charles Thomas
      Madison, WI
Re: Modifying a hash in a subroutine?
by mirod (Canon) on Aug 19, 2004 at 21:17 UTC

    It looks like you are doing a lot of ref to hash and hash to ref transformations. This might be simpler:

    modifyHash(\%my_hash); sub modifyHash { my $hash_ref = shift; # Do something to the hash $hash_ref->{'test'}=1; # no need for return, the original hash has been modified # the return value could be a success/failure flag }