开发者

How do I loop through a hash?

Given the following variable:

$test = {
  '1' => 'A',
  '2' => 'B',
  '3' => 'C',
  '4' => 'G',
  '5' => 'K',
}

How can loop through all assignments without knowing which keys I have?

I would like to fill a select box with 开发者_StackOverflowthe results as label and the keys as hidden values.


Just do a foreach loop on the keys:

#!/usr/bin/perl
use strict;
use warnings;

my $test = {
  '1' => 'A',
  '2' => 'B',
  '3' => 'C',
  '4' => 'G',
  '5' => 'K',
};

foreach my $key(keys %$test) {
    print "key=$key : value=$test->{$key}\n";
}

output:

key=4 : value=G
key=1 : value=A
key=3 : value=C
key=2 : value=B
key=5 : value=K


You can use the built-in function each:

while (my ($key, $value) = each %$test) {
  print "key: $key, value: $value\n";
}


You can find out what keys you have with keys

my @keys = keys %$test; # Note that you need to dereference the hash here

Or you could just do the whole thing in one pass:

print map { "<option value='$_'>$test->{$_}</option>"  } keys %$test;

But you'd probably want some kind of order:

print map { "<option value='$_'>$test->{$_}</option>"  } sort keys %$test;

… and you'd almost certainly be better off moving the HTML generation out to a separate template system.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜