AtomicPorkchop
AtomicPorkchop

Reputation: 2675

What happens a perl hash when I surround it in curly braces?

I am working a trying to understand how this one perl module works, it is called XML::Smart. Most of it was easy to figure out except for one thing that is not so much related to the module.

What I want to do is copy a hash from my script into the XML::Smart module for proccessing. After a little bit of "banning" on it I managed to make it do what I wanted. The problem is I don't what exactly I did. If someone could give a clue of why this works what it means in english that would be great.

I saw something like this when I was messing around with rolling my own modules in that meaning it had something to do with making a class, not sure if that is what it was called or it has anything similar.

Here is my code;

#!/usr/bin/perl
use strict;
use warnings;
use XML::Smart;

my $xml_obj = XML::Smart->new();

my %config_file = (
    "server01" => {
        "connection" => {
            "address" => "10.0.0.4",
            "port" => "22",
        }, "authentication" => {
            "username" => "admin",
            "password" => "password",
        },
    },
);

$xml_obj->{config} = {%config_file};

Upvotes: 1

Views: 255

Answers (2)

jmcneirney
jmcneirney

Reputation: 1384

If you're trying to assign %config_file to $xml_obj->{config} You'll want to do something like a hash slice.

@{ $xml_obj->{config} }{ keys %config_file } = values %config_file;

Upvotes: -1

Quentin
Quentin

Reputation: 944171

It creates a reference to a new hash with a (shallow) copy of the old hash.

{} is a hashref.

{ "foo", "bar", "x", "y" } defines a hashref with a list of keys and values.

If you put a hash inside {} it is in list context, so is turned into a list of keys and values.

Upvotes: 3

Related Questions