{ %hash } - a Dynamic Reference to a Hash

Contents | Up | Prev | Next

# 10.4. { %hash } - a Dynamic Reference to a Hash

In a similar way to the square brackets, putting a hash inside a pair of curly braces (`{ ... }`) will make it into a reference to a hash. Like an array reference, this reference is a scalar and can be used as an array element or a hash value. Plus, its own values can be references to other arrays or hashes.

To demonstrate this let's see the code of part of the contents table of this very lecture, to demonstrate the multi-level data structure capabilities of perl:

    use strict;
    use warnings;

    my $contents =
    {
        'title' => "Contents",
        'subs' =>
        [
            {
                'url' => "for",
                'title' => "The for loop",
                'subs' =>
                [
                    {
                        'url' => "next.html",
                        'title' => "Behaviour of next in the for loop",
                    },
                    {
                        'url' => "whence_for.html",
                        'title' => "Whence for?",
                    },
                ],
            },
            {
                'url' => "hashes",
                'title' => "Hashes",
                'subs' =>
                [
                    {
                        'url' => "functions.html",
                        'title' => "Hash Functions",
                    },
                ],
            },
            {
                'url' => "my",
                'title' => "Declaring Local Variables with \"my\"",
                'subs' =>
                [
                    {
                        'url' => "use_strict.html",
                        'title' => "\"use strict\", Luke!",
                    },
                ],
            },
            {
                'url' => "argv.html",
                'title' => "The \@ARGV array",
            },
        ],
        'images' =>
        [
            {
                'url' => 'style.css',
                'type' => 'text/css',
            }
        ],
    };

    sub get_contents
    {
        return $contents;
    }

Contents | Up | Prev | Next