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 | |
by davido (Cardinal) on Jun 30, 2006 at 09:02 UTC | |
by jeanluca (Deacon) on Jun 30, 2006 at 09:05 UTC |