Find key name in hash with only one key?

后端 未结 7 521
鱼传尺愫
鱼传尺愫 2021-02-03 22:37

If I have a hash

my %h = (
    secret => 1;
);

and I know that is only is one key in the hash, but I don\'t know what it is called.

7条回答
  •  不知归路
    2021-02-03 23:09

    my $k = each %h;
    

    However, you must remember to reset the iterator if you ever want to use it on the same hash again. Either another each will do it, or keys will, and if used in a scalar context, will avoid creating a list. So you can reset it with

    scalar keys %h; 
    # OR
    each %h;          # <- gets the undef
    my $k2 = each %h; # <- gets the first key
    

    So you could do it like this:

    my $k = ( scalar keys %h, each %h );
    

    But assuming it like reading JSON messages and stuff where you just want to read what's in the hash once and throw it away, it is probably the most succinct. However, if you want the variable right away, it's probably easier to do this:

    my ( $k, $v ) = each %$simple_JSON_structure;
    

提交回复
热议问题