Is it possible to nest associative arrays in Perl

Viewed 89

Just an academic question regarding nesting capabilities.

For example:

%inner = (1, "monday", 2, "tuesday"...);
%outer = ("hello", 1, "days", %inner);
2 Answers

The value in a hash is always a scalar, but it can be a hash reference.

my %outer = (hello => 1,
             days  => \%inner);

Or you can enter an anonymous hash directly:

my %outer = (hello => 1,
             days  => {1 => 'Monday',
                       2 => 'Tuesday',
                       ...});

Withour a reference, the "nested" hash is flattened, which is sometimes used to override default values:

my %conf = (%default, %specific);

Well you could always just have tried it. If you pass a reference of the first hash you can store it like a nested structure.

use Data::Dumper;

%inner = (1, "monday", 2, "tuesday"); 
%outer = ("hello", 1, "days", \%inner);
print(Dumper(\%outer));
print($outer{'days'}{2});

OUTPUT

$VAR1 = {
          'hello' => 1,
          'days' => {
                      '2' => 'tuesday',
                      '1' => 'monday'
                    }
        };
tuesday
Related