Skip to content
Complex Data Structures
step 1/5

Reading — step 1 of 5

Learn

~1 min readClosures and Data

Real Perl programs nest hashes and arrays deeply. The arrow operator -> chains accesses.

my $catalog = {
    fruits => [
        { name => "apple", price => 0.50 },
        { name => "banana", price => 0.30 },
    ],
    veggies => [
        { name => "carrot", price => 0.40 },
    ],
};

# Access:
$catalog->{fruits}[0]{name};         # "apple"
$catalog->{fruits}[0]{price};         # 0.50

# Modify:
push @{$catalog->{fruits}}, { name => "cherry", price => 1.00 };

The arrow -> between subscripts is optional$h->{a}->{b} is the same as $h->{a}{b}.

Walking nested structures:

for my $category (keys %$catalog) {
    print "$category:\n";
    for my $item (@{$catalog->{$category}}) {
        print "  $item->{name}: \$$item->{price}\n";
    }
}

The @{$ref} and %{$ref} syntax dereferences.

Data::Dumper for inspection:

use Data::Dumper;
print Dumper($catalog);

Cloning — be careful with shallow copies:

my %shallow = %$original;             # shallow — nested refs SHARED

use Storable qw(dclone);
my $deep = dclone($original);          # deep clone

Common pattern: counting / grouping:

my %word_counts;
$word_counts{$_}++ for split /\s+/, $text;

# By prefix:
my %by_letter;
push @{$by_letter{substr($_, 0, 1)}}, $_ for @words;

The push @{...} auto-vivifies — if the key didn't exist, Perl creates an empty arrayref, then pushes.

JSON interop with JSON::PP (core in modern Perl):

use JSON::PP;
my $json = encode_json($catalog);     # serialize
my $data = decode_json($json);         # parse

Storable for binary serialization:

use Storable;
store($catalog, "data.bin");
my $loaded = retrieve("data.bin");

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…