Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

keys function question

by raflach (Pilgrim)
on Jul 20, 2000 at 22:51 UTC ( #23467=perlquestion: print w/replies, xml ) Need Help??
raflach has asked for the wisdom of the Perl Monks concerning the following question:

if I have an object $obj that contains an element 'param' obtained by $obj->{'param'} that is a hash whose elements would be referenced by $obj->{'param'}{key}, and I want to iterate through the keys of this hash, i would try the following:
for my $key ( keys $obj->{'param'} ) { #do something with data }

That doesn't work, so I tried enclosing the hash in the following ways  keys {$obj->{'param'}} and  keys ($obj->{'param'}) and  keys [$obj->{'param'}] and all give me the similar errors... either
Type of arg 1 to keys must be hash ( not hash elem) at .... or Type of arg 1 to keys must be hash (not scalar ref constructor) at ... +.
I know I'm being stupid somehow... help

Replies are listed 'Best First'.
Re: keys function question
by tye (Sage) on Jul 20, 2000 at 22:57 UTC
    keys %{$obj->{param}}
Re: keys function question
by cwest (Friar) on Jul 20, 2000 at 22:58 UTC

      Okay, so I left off the "Enjoy!" and so ctweten's has gotten more votes than mine. ;)

      This discussion has been so short and to the point, I thought I'd add a bit...

      I dislike having to use the %{...} syntax as it is hard to read. One solution is:

      $ref= $obj->{param}; for( keys %$ref ) { Mung( $ref->{$_} ); }
      But what we really need is a post-fix operator that give you the whole hash (or array, or scalar, etc.) from a reference:
      my @keys= keys $obj->{param}->%;
      This was proposed on perl5-porters a while back but noone has submitted a patch (as far as I know) to implement it. So here is your chance to become famous. Go to the perl5-porters archive and read up on the proposal and you've got a great project for learning Perl guts.

        Oh C'mon, I voted you up, now you're winning :-)

        I'll have a few spare tuits comming soon.

        I'll have a look at this, sounds fun!

        I've never hacked Perl guts before but I'm willing to give it a shot.

        print foreach $r->%; print foreach $r->@; print foreach $r->$; print foreach $r->*;
        Enjoy! :-)
        I disagree. Referencing and derefencing should be pre-fix, and if you don't like the SIGIL{} syntax, add whitespace. $foo->\ is silly-looking. \$foo is not. $foo->% also looks silly to me, and if %$foo is too noisy, do %{ $foo }.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://23467]
Approved by root
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (3)
As of 2017-08-17 14:29 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (288 votes). Check out past polls.