Maps (aka Associative Arrays)

This page is under construction. Please come back later.
#!/usr/bin/env perl
use utf8;
use Utils;
use strict;
use warnings;
MAIN:
{
my $dictionary = {};
print "dictionary size: ", scalar(keys(%$dictionary)), "\n";
print "dictionary is ", (!scalar(%$dictionary) ? "empty" : "not empty"), "\n";
$dictionary->{"apple"} = "red";
$dictionary->{"banana"} = "yellow";
$dictionary->{"cantaloupe"} = "orange";
$dictionary->{"dragonfruit"} = "red";
$dictionary->{"elderberry"} = "purple";
print "dictionary size: ", scalar(keys(%$dictionary)), "\n";
print "dictionary is ", (!scalar(%$dictionary) ? "empty" : "not empty"), "\n";
print "bananas are ", $dictionary->{"banana"}, "\n";
my $x = "dragonfruit";
if (exists $dictionary->{$x}) {
print $x, " are ", $dictionary->{$x}, "\n";
} else {
print "Can't find ", $x, "\n";
}
$x = "fig";
if (exists $dictionary->{$x}) {
print $x, " are ", $dictionary->{$x}, "\n";
} else {
print "Can't find ", $x, "\n";
}
$x = "elderberry";
delete($dictionary->{$x});
if (exists $dictionary->{$x}) {
print $x, " are ", $dictionary->{$x}, "\n";
} else {
print "Can't find ", $x, "\n";
}
print Utils::mapToString($dictionary), "\n";
}
Output
$ perl Maps1.pl
dictionary size: 0
dictionary is empty
dictionary size: 5
dictionary is not empty
bananas are yellow
dragonfruit are red
Can't find fig
Can't find elderberry
{banana => yellow, cantaloupe => orange, dragonfruit => red, apple => red}
#!/usr/bin/env perl
use utf8;
use Utils;
use strict;
use warnings;
MAIN:
{
my $planet_diameters = {
"Mercury" => 4879,
"Venus" => 12103,
"Earth" => 12756,
"Mars" => 6794,
"Jupiter" => 142985,
"Saturn" => 120534,
"Uranus" => 51115,
"Neptune" => 49534,
"Pluto" => 2374,
"Ceres" => 946,
"Eris" => 2326,
"Makemake" => 1430
};
foreach my $planet (keys(%$planet_diameters)) {
print $planet, " has a diameter of ", $planet_diameters->{$planet}, " km\n";
}
}
Output
$ perl Maps2.pl
Mars has a diameter of 6794 km
Saturn has a diameter of 120534 km
Uranus has a diameter of 51115 km
Ceres has a diameter of 946 km
Mercury has a diameter of 4879 km
Makemake has a diameter of 1430 km
Pluto has a diameter of 2374 km
Jupiter has a diameter of 142985 km
Venus has a diameter of 12103 km
Earth has a diameter of 12756 km
Neptune has a diameter of 49534 km
Eris has a diameter of 2326 km
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
References
- [[Perl Language Reference]]
- [[Comprehensive Perl Archive Network (CPAN)]]
- [[Beginning Perl]], Simon Cozens
- [[Perl Monks Tutorials]]
Pure Programmer


