Hash of arrays in Perl
One key, many values: the workhorse structure for grouped data.
use strict;
use warnings;
my %tags = (
perl => ["regex", "sigils"],
python => ["indent"],
);
# push through the reference grows the inner array
push @{ $tags{perl} }, "context";
push @{ $tags{python} }, "batteries";
for my $lang (sort keys %tags) {
my $count = scalar @{ $tags{$lang} };
print "$lang ($count): @{ $tags{$lang} }\n";
}
How it works
- Each value in
%tagsis an anonymous array built with[...]. push @{ $tags{perl} }grows the inner array through its reference.- The loop interpolates
@{ $tags{$lang} }to print each list in place.
Keywords and builtins used here
forkeysmyprintpushscalarsortuse
The run, in numbers
- Lines
- 16
- Characters to type
- 338
- Tokens
- 84
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 78 seconds.
Step 2 of 3 in References & structures, step 20 of 27 in Language basics.