http://qs321.pair.com?node_id=407813


in reply to Re: Setting variables inside a hash: newbie question
in thread Setting variables inside a hash: newbie question

Ben is absolutely right - pass a hash *by reference* - that is, pass a reference to a hash instead of the hash itself.

One concept that Ben didn't mention that I think is worth acknowledging is that when parameters are passed to a subroutine, that argument list is "flattened" out into a list of scalars - arrays are flattened out into a list of scalars, and hashes are flattened out into a list of scalars - the result is one big list of scalars getting passed to the subroutine. This isn't a problem unless you pass an array or hash first, and *then* other parameter(s) - the array or hash that receives the 1st argument in the subroutine will likely "swallow up" all the arguments being passed in, since it can't tell from the one big "list" of scalars coming in which ones are intended for it and which ones are intended for other parameters.

To avoid confusion when passing "things" to subroutines, pass each parameter as a scalar - this means

* passing scalars as themselves * passing a "reference to an array" (which is itself a scalar) instead of the array itself * passing a "reference to a hash" (which is itself a scalar) instead of the hash itself
Then if you really want to work with a "copy" of the array or hash (instead of just using the reference to refer to elements in the array or hash) whose reference was passed into the subroutine, you can create a copy like this:
sub do_something($my_scalar, $my_arrayref, $my_hashref) { my @my_array = @$my_arrayref; my %my_hash = %$my_hashref; ### more code here ### }
HTH.