Quick Reference Guide to Array and Hash Manipulations
Array Manipulations
1. Do something to each item in an array:
foreach $item (@array) {
# do something to $item;
}
2. Find the items in an array which match the condition:
@match = grep { $_ == 1 } @array;
Hash Manipulations
1. To initialize a hash
%food_color = (
“apple” => “red”,
“banana => “yellow”,
“lemon” => “yellow”,
“carrot” => “orange”
);
2. Print the hash keys
foreach $food (keys %food_color) {
print “$food\n”;
}
3. Check if item is a hash key
foreach $name (“banana”, “martini”) {
if (exists $food_color{$name}) {
print “$name is a food.\n”;
} else {
print “$name is a drink.\n”;
}
}
4. Do something with each key and value in a hash
while (($food, $color) = each(%food_color)) {
print “$food is $color.\n”;
}
Alternatively
foreach $food (sort keys %food_color) {
print “$food is $food_color{$food}.\n”;
}
5. Find the items in a hash which match the condition:
@match = grep { $hash{$_} == 1 } keys %hash;