Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

foreach keys possible using a hash reference?

by c (Hermit)
on Jul 04, 2002 at 16:57 UTC ( #179494=perlquestion: print w/replies, xml ) Need Help??

c has asked for the wisdom of the Perl Monks concerning the following question:

I am passing a hash to a subroutine as a reference, e.g. &thing(\%hash); The subroutine then pulls in the hash values with my $args = shift; and I call the values using $args->{key}. Is there a manner of running thru the "keys" of this hash reference, even though its now a scalar, rather than an actual hash?

thanks -c

Replies are listed 'Best First'.
Re: foreach keys possible using a hash reference?
by Abigail-II (Bishop) on Jul 04, 2002 at 17:10 UTC
    The rule on what the syntax is when dealing with references is very simple. Wherever you use something of the form sigil followed by the name of a variable (scalar, hash, array, subroutine), you may replace the name of the variable with a block whose result is a reference to the appropriate type.

    So, where you normally would write

    keys %hash
    you now replace hash with a block returning a reference to a hash, and you get:
    keys %{$hashref}
    The block has a very, very simple statement, the statement is just an expression consisting of a single variable. As an extra feature, in such a simple expression, you may omit the braces, so you will end up with:
    keys %$hashref

    Abigail

Re: foreach keys possible using a hash reference?
by gav^ (Curate) on Jul 04, 2002 at 17:03 UTC
    Something like this would do the trick:
    foreach (keys %$args) { # do something }

    gav^

Re: foreach keys possible using a hash reference?
by amphiplex (Monk) on Jul 04, 2002 at 17:04 UTC
    this should do:
    my %h = ( 'a' => 1, 'b' => 2, 'c' => 3, ); print_hash(\%h); sub print_hash { my $h = shift; for (keys %$h) { print "$_: $h->{$_}\n"; } }
    ---- kurt
Re: foreach keys possible using a hash reference?
by impossiblerobot (Deacon) on Jul 04, 2002 at 21:53 UTC
    I would also suggest perlreftut, which details five simple rules for creating and de-referencing references, and really simplifies things.

    Impossible Robot
Re: foreach keys possible using a hash reference?
by Juerd (Abbot) on Jul 04, 2002 at 19:48 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://179494]
Approved by gav^
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2021-06-14 21:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (66 votes). Check out past polls.

    Notices?