You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl中批量为JSON对象添加多值报错,求正确写法

Perl批量为JSON解码对象赋值及添加空对象的正确方法

你尝试的批量写法不符合Perl语法,因此会抛出Can't modify constant item in scalar assignment错误。以下是几种可行的解决方案:

方案一:简化重复路径,逐个赋值(保留原有键值)

先将重复访问的目标哈希引用存入临时变量,再逐个赋值,同时添加空对象:

my $target_hash = $codes->{product}->{ad_id}->{$ad_id};
$target_hash->{singlePay} = $singlePayments;
$target_hash->{trialPay} = $trialPayments;
$target_hash->{subsPay} = $subsPayments;
$target_hash->{affs} = {}; # 添加空对象

方案二:使用哈希切片批量赋值

利用Perl的哈希切片特性,一次性给多个键赋值,代码更紧凑:

my $target_hash = $codes->{product}->{ad_id}->{$ad_id};
@{$target_hash}{qw(singlePay trialPay subsPay)} = ($singlePayments, $trialPayments, $subsPayments);
$target_hash->{affs} = {};

方案三:直接替换为新哈希(覆盖原有内容)

如果目标位置原本没有需要保留的键值对,可以直接将该位置替换为包含所有所需键值的新哈希引用,同时包含空对象:

$codes->{product}->{ad_id}->{$ad_id} = {
    singlePay => $singlePayments,
    trialPay  => $trialPayments,
    subsPay   => $subsPayments,
    affs      => {}
};

注意:方案三会覆盖目标位置原有的所有键值对,仅适合该位置无需要保留的数据时使用。

内容的提问来源于stack exchange,提问作者Chris Brown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 12:07:10