Skip to content
Perl

Complex Data Structures

Build nested structures with references.

#reference#data-structure

Code

perl
use strict;
use warnings;
use Data::Dumper;

# Array of arrays (matrix)
my @matrix = (
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
);
print $matrix[1][2];  # 6

# Hash of arrays
my %classes = (
  fruits => ["apple", "banana"],
  veggies => ["carrot", "pea"],
);
push @{$classes{fruits}}, "cherry";
print $classes{fruits}[2];  # cherry

# Array of hashes (records)
my @users = (
  { id => 1, name => "Alice", roles => ["admin", "user"] },
  { id => 2, name => "Bob",   roles => ["user"] },
);
for my $u (@users) {
  print "$u->{id}: $u->{name} (@{$u->{roles}})\n";
}

# Hash of hashes
my %config = (
  db => { host => "localhost", port => 5432 },
  cache => { host => "redis", port => 6379 },
);
print $config{db}{host};  # localhost

# Deep copy (avoid shared references)
my @copy = map { { %$_ } } @users;

# Pretty print
print Dumper(\%config);