typestar

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

  1. => pairs keys with values; assigning to $score{alan} adds a key in place.
  2. sort keys %score walks the keys in order; interpolation reads each value.
  3. delete removes a pair; exists asks about a key without creating it.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Scalars & sigils, step 3 of 27 in Language basics.

← Previous Next →

Hashes in other languages