Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^2: hash from sub directly into foreach loop

by jeanluca (Deacon)
on Jun 30, 2006 at 08:23 UTC ( [id://558531]=note: print w/replies, xml ) Need Help??


in reply to Re: hash from sub directly into foreach loop
in thread hash from sub directly into foreach loop

nope, the sub should return a hash and not a hash reference. It should be the same as with
foreach( keys CGI::Vars() )
because that is what I'm trying to do!

LuCa

Replies are listed 'Best First'.
Re^3: hash from sub directly into foreach loop
by gellyfish (Monsignor) on Jun 30, 2006 at 10:58 UTC

    You can't "return a hash" from a subroutine, you can only return a list, the effect of return %hash is to flatten the hash into a list of key => value pairs. Thus the effect of the the three following subroutines is similar (the order of the hash keys in the first aside:)

    sub foo { my %foo = ( Foo => '1', Bar => '2'); return %foo; } + sub bar { my @bar = qw(Foo 1 Bar 2); return @bar; } + sub baz { return 'Foo','1','Bar','2'; } + print foo(),"\n"; print bar(),"\n"; print baz(),"\n";

    This is why people are telling you to return a hash reference as this is the only way to retain the, er, hashiness after the appropriate dereferencing.

    /J\

Re^3: hash from sub directly into foreach loop
by Corion (Patriarch) on Jun 30, 2006 at 08:32 UTC

    Please show working code which does what you're trying to do. When I try the following, it doesn't work:

    Q:\>perl -MCGI -le "foreach( keys CGI::Vars() ) { print }" Type of arg 1 to keys must be hash (not subroutine entry) at -e line 1 +, near ") ) " Execution of -e aborted due to compilation errors.

    When I try the following, which the documentation and davidj suggest, it works (in the sense of not being a syntax error). But that works by returning a hash reference:

    Q:\>perl -MCGI -le "foreach( keys %{ CGI::Vars() }) { print }" Q:\>

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://558531]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-04-20 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found