in reply to Passing a hash, and a scalar to subroutine

Insert this line at the start of the sub, before %new_data is initialized:

my $scalar_data = shift;

See perldoc -f shift for an explanation of shift, and what it does with no parameters. I should note that you had already selected the proper order (scalar then hash) to do this as easily as possible.

mhoward - at - hattmoward.org

Replies are listed 'Best First'.
Re^2: Passing a hash, and a scalar to subroutine
by gorillaman (Acolyte) on Jul 17, 2004 at 05:11 UTC
    Ahh.. Thank you so much, that definetely cleared things up. The "shift" was exactly what I needed. This one had me stumped. I have a lot to learn. It seems the more I learn, the dumber I get. Anyway, Thank you!
      A hash in list context, such as a subroutine argument list, gets converted to a list of key,value pairs. So you are actually passing three arguments in your example code. One is the scalar, and the key and value of the single hash entry. Inside the sub, you convert the argument list back into a hash. The rule here is that the elements in the list are entered into the hash as key1 => value1, key2 => value2 and so forth. (The "=>" is just another way of writing "," but it emphasizes the pairing between key and value.) So your three elements get assigned into the hash as scalar => key1, value1 => undef, which makes a "hash" out of the whole deal. Since you only have three elements, Perl helpfully supplies the undef value as the fourth value in the list. Doing the shift removes the scalar from the argument list and leaves two elements, which assign back into the hash as you desire.