What's the safest way to iterate through the keys of Perl hash if you are an expert Perl developer?
foreach my $key (keys %hash) { ... }
foreach my $val (values %hash) { ... }
keys %hash; # reset the internal iterator so a prior each() doesn"t affect the loop
while(my($k, $v) = each %hash) { ... }
%h = (a => 1, b => 2);
foreach my $k (keys %h)
{
$h{uc $k} = $h{$k} * 2;
}
(a => 1, A => 2, b => 2, B => 4)
%h = (a => 1, b => 2);
keys %h;
while(my($k, $v) = each %h)
{
$h{uc $k} = $h{$k} * 2; # BAD IDEA!
}
(a => 1, A => 2, b => 2, B => 8)
keys %h;
while(my($k, $v) = each %h)
{
if(...)
{
delete $h{$k}; # This is safe
}
}
% perldoc -f keys
% perldoc -f each
Tags: iteration perl hash each
Source: By Rudd Zwolinski as answer to the question
This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 2.5
Related code-snippets:
- Redefining an attribute in Python with an index in array of objects using 'in'. If no object is found in an array of objects then it is not correct.
- Why can't I force either array ref or scalar to be array in Perl?
- How do you create a sparse array?
- How do I remove duplicates from a Perl application?
- What is the best way to create objects in Perl?
- Assignment inside Perl ternary conditional operator problems. Assignment inside Perl ternary conditional operator problems.
- How do you retrieve selected text using Regex in C#?
- Is it possible to parse attributes in Perl using regex?
- How do I determine the type of blessed reference in Perl?
- Why are my Perl Maps not returning anything?
- How can I tell if variable has numeric value in Perl?
- Replacement for for... if array iteration is used.
- How can I test STDIN without blocking in Perl?
- How can I create sdbm hash function in C#?
- How can a Perl system print commands that it is running?