'Perl - hash->Yaml->hash reduces quotation marks in numbers:
I'm trying to insert a hash to a YAML file and later return it to the original hash. (I'm doing it because I'm using multiple threads and want to merge them all at the end).
This is my code:
#!/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);
The output is:
$VAR1 = {
'hello' => 234
};
I would have expected the value to be '234' and not just 234. Any ideas how could I return it to '234'?
Thanks :)
EDIT: I was told there is no difference in perl between those options and that perl relates to everything the same. That's enough for me.
Solution 1:[1]
YAML.pm and YAML::XS might not handle numbers and strings correctly. YAML.pm is old anyway and shouldn't be used anymore.
While it is true that strictly there is no 100% reliable way to differentiate between numbers and strings, the variables have certain internal flags, and as long as they don't change, you can use YAML::PP which will handle the flags (in the same way as currently JSON::PP does) to differentiate between numbers and strings by making a good guess. Simply replace your usage of YAML and YAML::XS with YAML::PP:
use YAML::PP qw( Load Dump );
and the output will be
$VAR1 = {
'hello' => '234'
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tinita |
