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

Perl中hash转YAML再转回hash时数值类字符串引号丢失问题

Perl哈希与YAML互相转换问题

需求背景

我尝试将Perl的hash写入YAML文件,后续再将其还原为原始hash,该操作背景是我使用多线程开发,需要在最终阶段合并所有线程的处理结果。

实现代码

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
use YAML::XS;
use YAML qw(Dump);

sub PrintHash2Yaml {
    my ( $hash2Yaml, $yamlfilename ) = @_;

    open( FH, ">$yamlfilename.yaml" ) or die "can't open $yamlfilename.yaml : $!\n";
    print FH Dump($hash2Yaml);
    close FH;
}

sub yaml2Hash {
    my ($yamlfilename) = @_;

    # step 1: open file
    open my $fh, '<', "$yamlfilename.yaml" or die "can't open config file: $yamlfilename $!";

    # step 2: slurp file contents
    my $yml = do { local $/; <$fh> };

    # step 3: convert YAML 'stream' to perl hash ref
    my $yaml2hash = Load($yml);

    my $hashDebug = Dumper($yaml2hash);
    open( FH2, ">$yamlfilename.hash2" ) or die "can't open $yamlfilename.hash2 : $!\n";
    print FH2 $hashDebug;
    close FH2;

    return $yaml2hash;
}


my $hash1 = { 'hello' => '234' };
PrintHash2Yaml($hash1, "ex1");
my $hash3 = yaml2Hash("ex1");

print Dumper($hash3);

运行输出

$VAR1 = {
          'hello' => 234
        };

问题描述

我原本预期hello对应的value值是带引号的'234',而非无引号的234,请问有什么方法可以将值还原为带引号的'234'?

后续补充结论

后续我了解到Perl中带引号的'234'和不带引号的234没有差异,Perl对二者的处理逻辑完全一致,该结论已经满足我的需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:12:03