Liam Liam - 7 months ago 8
Perl Question

Access the key value from an associative array

I have the associative array

%cart_item
, within this is a series of associative arrays. I need to access the value of the keys within
%cart_item
. I have the following code which iterates on each array key. (I do the equivalent of php's continue if the value is 'meta')

my $key_value;
for (keys %cart_item) {
next if (/^meta$/ || /^\s*$/);

}


I need to do something like this though (although this isn't valid), setting the value of the keys in the loop:

my $key_value;
for $i (keys %cart_item) {
next if (/^meta$/ || /^\s*$/);
$key_value = $i;
# do stuff
}


Could anyone suggest a solution here? Apologies if this is obvious, I'm a Perl newbie. Thanks

Answer

I think you are asking for

for my $key (keys %cart_item) {
   next if $key =~ /^meta$/ || $key =~ /^\s*$/;

   my $val = $cart_item{$key};
   ...
}
Comments