在Perl中使用结构和哈希

在Perl中使用结构和哈希,perl,Perl,考虑Perl中的以下结构:(让我们称之为声明A) 我有一个散列%hash,其中包含自定义字段(我不知道有多少)。它看起来像这样: $VAR1 = { 'key2' => '123', 'key1' => 'abc', 'key3' => 'xwz' }; foreach my $key (keys %hash) { push @{ $json_struct }, { $key => $hash{$key}

考虑Perl中的以下结构:(让我们称之为声明
A

我有一个散列
%hash
,其中包含自定义字段(我不知道有多少)。它看起来像这样:

$VAR1 = {
         'key2' => '123',
         'key1' => 'abc',
         'key3' => 'xwz'
    };
foreach my $key (keys %hash) {
  push @{ $json_struct }, { $key => $hash{$key} };
}
my $foo = {
    name => $name,
    time => $time,
};

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

my $combined = {
    %{$foo},
    %{$bar},
};
我想循环遍历散列键并将这些键插入到结构中,所以我想我可以这样做:

$VAR1 = {
         'key2' => '123',
         'key1' => 'abc',
         'key3' => 'xwz'
    };
foreach my $key (keys %hash) {
  push @{ $json_struct }, { $key => $hash{$key} };
}
my $foo = {
    name => $name,
    time => $time,
};

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

my $combined = {
    %{$foo},
    %{$bar},
};
我不确定它是否按预期工作。还有,有没有更干净的方法?也许我可以在声明
A
时将其组合成一行或两行

预期输出:(顺序无关紧要)


$json_struct
是一个散列引用,但是
@{$json_struct}
$json_struct
执行数组解引用,因此这不起作用

哈希没有
push
操作符;您只需通过将值指定给新键来插入新数据。对于你的结构,你只想说

foreach my $key (keys %hash) {
    $json_struct->{$key} = $hash{$key};
}
现在您还可以使用
@{…}
操作符指定一个,这可能就是您所想的。哈希片可用于同时对哈希的多个键进行操作。该操作适用的语法是

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

$json_struct
是一个散列引用,但是
@{$json_struct}
$json_struct
执行数组解引用,因此这不起作用

哈希没有
push
操作符;您只需通过将值指定给新键来插入新数据。对于你的结构,你只想说

foreach my $key (keys %hash) {
    $json_struct->{$key} = $hash{$key};
}
现在您还可以使用
@{…}
操作符指定一个,这可能就是您所想的。哈希片可用于同时对哈希的多个键进行操作。该操作适用的语法是

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

连接哈希的最简单方法如下所示:

$VAR1 = {
         'key2' => '123',
         'key1' => 'abc',
         'key3' => 'xwz'
    };
foreach my $key (keys %hash) {
  push @{ $json_struct }, { $key => $hash{$key} };
}
my $foo = {
    name => $name,
    time => $time,
};

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

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

连接哈希的最简单方法如下所示:

$VAR1 = {
         'key2' => '123',
         'key1' => 'abc',
         'key3' => 'xwz'
    };
foreach my $key (keys %hash) {
  push @{ $json_struct }, { $key => $hash{$key} };
}
my $foo = {
    name => $name,
    time => $time,
};

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

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

谢谢你的回答。如果哈希为空,它仍将按预期工作?($json_struct将只包含名称和时间?)是的,不会运行
foreach
循环的迭代,并且空的哈希片将是不可操作的。谢谢您的回答。如果哈希为空,它仍将按预期工作?($json_struct将只包含名称和时间?)是的,不会运行
foreach
循环的迭代,并且空的哈希片将是不可操作的。