Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 476
Thariama Avatar asked Nov 28 '25 09:11

Thariama


2 Answers

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
like image 89
Toto Avatar answered Nov 29 '25 22:11

Toto


You can use the built-in function each:

while (my ($key, $value) = each %$test) {
  print "key: $key, value: $value\n";
}
like image 36
Naveed Avatar answered Nov 30 '25 00:11

Naveed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!