Search code examples
perlhashperl-data-structures

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 the results as label and the keys as hidden values.


Solution

  • 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