View Category

Define an empty map

perl
# %map = {}
# This was wrong, that would have created a hash with one key
# of the stringified hash reference (HASH(0xNUMBERSHERE)) and a
# value of 'undef', as well as triggering a
# "Reference found where even-sized list expected" with the warnings
# pragma enabled

my %map;

Define an unmodifiable empty map

perl
# perl does not provide unmodifiable maps/hashes, but you could use "constant
# functions", if you really need them
# 2011-07-06 Not actually true, see Hash::Util::lock_hash;

sub MAP () { {} }
use Hash::Util qw/lock_hash/;
# two lines
my %hash;
lock_hash(%hash);
# or in one line
lock_hash(my %locked_hash);

Define an initial map

Define the map {circle:1, triangle:3, square:4}
perl
%map = (circle => 1, triangle => 3, square => 4);

Check if a key exists in a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print "ok" if an pet exists for "mary"
perl
%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if ($pets{'mary'});
%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if $pets{'mary'};
print 'ok' if $pets{mary};
print 'ok' if exists $pets{mary}
Starting with a previously suggested solution:

%pets = (joe => 'cat', mary => 'turtle', bill => 'canary');
print 'ok' if $pets{'mary'};

.. there is a case where this will not work as expected- for the case where mary => 0 ..

suggest instead to use the following conditional check if a value of 0 is allowable.:

print 'ok - is defined' if defined $pets{'mary'};

Retrieve a value from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} print the pet for "joe" ("cat")
perl
%pets = (joe => 'cat', mary => 'turtle', bill=>'canary');
print $pets{joe};

Add an entry to a map

Given an empty pets map, add the mapping from "rob" to "dog"
perl
$pets{rob} = 'dog';

Remove an entry from a map

Given a map pets {joe:cat,mary:turtle,bill:canary} remove the mapping for "bill" and print "canary"
perl
print delete $pets{bill};

Create a histogram map from a list

Given the list [a,b,a,c,b,b], produce a map {a:2, b:3, c:1} which contains the count of each unique item in the list
perl
foreach(@list) {
$histogram{$_}++;
}
$histogram{$_}++ for @list;

Categorise a list

Given the list [one, two, three, four, five] produce a map {3:[one, two], 4:[four, five], 5:[three]} which sorts elements into map entries based on their length
perl
@list = qw(one two three four five);
push @{$map{length($_)}}, $_ for (@list);