Skip to content
Perl

Complex Data Structures

Build nested structures with references.

By EZ4Code Team
referencedata-structure

Code

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);

Explanation

Perl's flat data model means nested structures require references. [] and {} create anonymous arrays/hashes. The arrow between subscripts is optional: $arr[0][1] == $arr[0]->[1]. @{$ref} dereferences an array ref; %{$ref} a hash ref. Use Data::Dumper for debugging complex structures. For deep copies, use Storable::dclone or Clone module.

More Perl Snippets