Hash Idioms
Get to know about hash idioms and locking hashes in Perl.
Finding unique values with undef
Each key exists only once in a hash, so assigning multiple values to the same key stores only the most recent value. This behavior has advantages! For example, we can find unique elements of a list:
Press + to interact
my @items = ('Pencil', 'Sharpner', 'Pencil', 'Eraser', 'Paper', 'Eraser');my %uniq;undef @uniq{ @items };my @uniques = keys %uniq;say "@uniques";
Using undef
with a hash slice sets the hash values to undef
. This idiom is the cheapest way to perform set operations with a hash.
Press + to interact
Counting occurrences
Hashes are useful for counting elements, such as IP addresses in a log file:
Press + to interact
main.pl
log
sub analyze_line { split /\s/, shift; }open(my $logfile, '<', 'log');my %ip_addresses;while (my $line = <$logfile>) {chomp $line;my ($ip, $resource) = analyze_line( $line );$ip_addresses{$ip}++;}close($logfile);#printing the hashfor (keys %ip_addresses) {say "$_ => $ip_addresses{$_}";}
The initial value of a hash value is undef
. The post-increment operator ++
treats that as zero. This in-place modification ...