TTaJTa4
TTaJTa4

Reputation: 840

Working with structures and hashes in Perl

Consider the following structure in Perl: (let's call it declaration A)

my $json_struct = {
    name => $name,
    time => $time,
};

I have a hash %hash which contains custom fields (I don't know how many). It looks something like this:

$VAR1 = {
         'key2' => '123',
         'key1' => 'abc',
         'key3' => 'xwz'
    };

I would like to loop through the hash keys and insert those keys into the structure, so I thought that I can do something like this:

foreach my $key (keys %hash) {
  push @{ $json_struct }, { $key => $hash{$key} };
}

I'm not sure that it is working as expected. Also, is there a cleaner way to do so? Maybe I can combine it in one or two lines while declaring A.?

Expected output: (order does not matter)

$VAR1 = {
         'name' => $name,
         'time' => $time,
         'key2' => '123',
         'key1' => 'abc',
         'key3' => 'xwz'
    };

Upvotes: 0

Views: 38

Answers (2)

mob
mob

Reputation: 118665

$json_struct is a hash reference, but @{ $json_struct } performs array dereferencing on $json_struct, so that is not going to work.

There is no push operator for hashes; you just insert new data by assigning values to new keys. For your structure, you would just want to say

foreach my $key (keys %hash) {
    $json_struct->{$key} = $hash{$key};
}

Now you can also use the @{...} operator to specify a hash slice, which may be what you were thinking of. Hash slices can be used to operate on several keys of a hash simultaneously. The syntax that will work for you for that operation is

@{$json_struct}{keys %hash} = values %hash;

Upvotes: 1

Andy Lester
Andy Lester

Reputation: 93795

The easiest way to join hashes is like this:

my $foo = {
    name => $name,
    time => $time,
};

my $bar = {
         'key2' => '123',
         'key1' => 'abc',
         'key3' => 'xwz'
    };

my $combined = {
    %{$foo},
    %{$bar},
};

Upvotes: 1

Related Questions