in reply to Trouble passing hash into function

Are you passing the hash:

use strict; use warnings; use Data::Dump::Streamer; my %hash = (a => 1, b => 2, c => 3); printHash (%hash); sub printHash { my %subHash = @_; print "$_ => $subHash{$_}\n" for keys %subHash; }

Prints:

c => 3 a => 1 b => 2

or a reference to the hash:

... printHash (\%hash); sub printHash { my ($subHash) = @_; print "$_ => $subHash->{$_}\n" for keys %$subHash; }

which prints as above. Or are you doing something else? If the snippets above don't clear the problem up, generate a similar sample demonstrating the problem and show it to us.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Trouble passing hash into function
by dbonneville (Acolyte) on Sep 05, 2007 at 23:10 UTC
    Hmmm...I tried to get my head around references and hard references. I thought a hard reference has the \ in front of it. I was passing the hash, as I posted just a minute ago, with the \ infront of it.

    Can you explain the difference between "my %subhash" and "my (%subhash)" in your examples? I would have never in a million years (well, maybe) gotten to the point where I would tried parenthesis around a variable. They look optional to me.

    Regardless, I took off the \ where I passed the hash to the function...and it worked. I'm very relieved at the moment, but have no understanding about why this works, which is troubling after trying so hard to understand this.

    Thanks again!

    Doug

      For the low down on Perl references see perlref. You will probably find that perlsub helps too.

      The important bits are:

      The Perl model for function call and return values is simple: all functions are passed as parameters one single flat list of scalars

      and:

      Any arrays or hashes in these call and return lists will collapse, losing their identities

      in:

      my (...) = @_;

      the () provides a list context for the assignment so the elements in @_ are assigned in turn to the variables in (...). In the sample code there happens to be only one element in the list and we could instead have used one of:

      my $hash = $_[0]; my $hash = shift;

      instead. If you omit the (), then the assignment sees a scalar and assigns the number of elements in @_ to $hash rather than the contents of the first element.


      DWIM is Perl's answer to Gödel

      You would have to put a backslash in front of it normally, but because you've prototyped your sub Perl takes the reference for you behind the scenes and you receive that ref in $_[0] rather than the normal behavior of the hash being flattened into a list and you getting the key/value pairs in @_.

      Of course one might feel inclined to yet again comment on the undesirability of prototypes, but I'm getting weary of doing so . . .

        Thanks! I'll have to read up on prototypes. I barely follow the logic of why my program works at all at the moment.

        Doug