Hashes in Perl
Perl's key-value shape: % for the whole hash, $ plus curly braces for one value.
use strict;
use warnings;
my %score = (ada => 95, grace => 88);
$score{alan} = 91;
# one value wears the scalar sigil and a curly-brace key
print "ada scored $score{ada}\n";
for my $name (sort keys %score) {
print "$name => $score{$name}\n";
}
delete $score{alan};
print "linus in? ", (exists $score{linus} ? "yes" : "no"), "\n";
print scalar(keys %score), " entries left\n";
How it works
=>pairs keys with values; assigning to$score{alan}adds a key in place.sort keys %scorewalks the keys in order; interpolation reads each value.deleteremoves a pair;existsasks about a key without creating it.
Keywords and builtins used here
deleteexistsforkeysmyprintscalarsortuse
The run, in numbers
- Lines
- 16
- Characters to type
- 379
- Tokens
- 84
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 78 seconds.
Step 3 of 3 in Scalars & sigils, step 3 of 27 in Language basics.