Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Modifying a hash in a subroutine?

by C_T (Scribe)
on Aug 19, 2004 at 21:08 UTC ( [id://384458]=perlquestion: print w/replies, xml ) Need Help??

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 }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://384458]
Approved by NovMonk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2024-03-28 11:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found