in reply to hash from sub directly into foreach loop

There are a few problems. One is that %s{'a'} = 10; won't compile. You mean to say, $s{'a'} = 10;

The next problem is that testa() returns a flat list of keys and values, not a hash. You could re-hashify them like this:

%{ { testa() } }

This takes the return value of testa() (a flat list of keys interlaced with values), absorbs that list into an anonymous hash (the inner set of {...} does this), and then dereferences that anonymous hash ref (the outter %{ ..... } does this).

But even then you still have a problem. Your loop will print a list of keys, sure enough. But how are you going to access the values if nothing is holding onto that hash ref?

Try this instead:

while( my( $key, $val ) = each( %{ { testa() } } ) { print "Key: $key\tValue: $val\n"; }

...or better yet, pass by reference, as described in perlsub:

while( my( $key, $val ) = each( %{ testa() } ) { print "Key: $key\tValue: $val\n"; } sub testa { my %s = ( a => 10, b => 20, c => 30 ); return \%s; }

Dave

Replies are listed 'Best First'.
Re^2: hash from sub directly into foreach loop
by jeanluca (Deacon) on Jun 30, 2006 at 08:47 UTC
    sorry for all the confusion about the typo.

    But thnx for the %{ { &testa } } that does the trick!
    I guess it might be very usefull to study the perlsub (how do you guys make this a link, where is it documented, I've search the docs already a couple of times ?)!!

    LuCa

      You're welcome, but I did say %{ { testa() } }, not %{ { &testa } }. Your specific example code doesn't bump into the difference, but there is a difference. It's just good to be in the habit of using the subroutine() method of calling subs, instead of the Perl4-ish (and sometimes confusing) &subroutine method.

      As for how to link to perlsub, see About the PerlMonks FAQ, and specifically, What shortcuts can I use for linking to other information?. ...but first read perlsub; that's a much more important step toward your understanding Perl.


      Dave

        thnx a lot!!