Wednesday, April 13, 2011

How to Loop Through a Perl Hash (With Examples)

# 1. Standard Iteration (Unordered)
# The 'keys' function returns a list of all keys in the hash. 
# Hashes are inherently unordered, so the keys will come out in a random sequence.

foreach my $key ( keys %hash ) {
    # Look up the value associated with the current key
    my $value = $hash{$key}; 
}

# 2. Sorted Iteration
# The 'sort' function automatically orders the list of keys alphabetically 
# before passing them to the loop, ensuring predictable output.

foreach my $key ( sort keys %hash ) {
    my $value = $hash{$key};
}

# 3. Filtered Iteration
# The 'grep' function evaluates a regular expression against the keys.
# This loop will only process keys that begin with the exact string "text:".

foreach my $key ( grep /^text:/, keys %hash ) {
    my $value = $hash{$key};
}

# 4. Simultaneous Key/Value Iteration
# The 'each' function returns both the key and the value at the same time.
# This is often more memory efficient for extremely large hashes because 
# it doesn't need to generate a list of all keys upfront like the 'keys' function does.

while( my( $key, $value ) = each( %hash ) ) {
    # Both $key and $value are already assigned and ready to use here
}

No comments: