Skip to content

Instantly share code, notes, and snippets.

@kanonji
Created April 26, 2012 14:39
Show Gist options
  • Save kanonji/2500011 to your computer and use it in GitHub Desktop.
Save kanonji/2500011 to your computer and use it in GitHub Desktop.
[SOLVED]JSONをパースしてキーに入ってる配列を扱う際、期待した動きにならないけど、どうしてだろう?
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use feature qw/say/;
use Encode;
use Data::Dumper;
use JSON;
use File::Slurp qw/read_file write_file/;
my $json = JSON::decode_json File::Slurp::read_file 'data.json';
say 'confirm ref() shows type only with reference';
my @array = (1,2,3);
print 'say @array: ';
say @array;
print 'say ref @array; ';
say ref @array;
my $ref =\@array;
print 'say $ref; ';
say $ref;
print 'say ref $ref: ';
say ref $ref;
say '-----------------------------------';
foreach my $key (keys %$json){
say sprintf 'In foreach loop. key is now "%s"', $key;
my $type = ref $json->{$key};
say sprintf '$json->{$key} is %s', $type;
say '-----------------------------------';
say 'foreach my $item (@array)';
say 'unexpected behavior...';
my @array = $json->{$key};
foreach my $item (@array){
say Dumper $item;
}
say '-----------------------------------';
say 'foreach my $item (@$ref)';
say 'expected behavir!';
my $ref = $json->{$key};
foreach my $item (@$ref){
say Dumper $item;
}
say '-----------------------------------';
say 'advised solution.';
say 'that unexpected behavior is because $json->{$key} gives array ref. not array';
say 'expected behavir!';
my @array2 = @{$json->{$key}};
foreach my $item (@array2){
say Dumper $item;
}
}
{
"foo": [{
"key": 1
},{
"key": 2
},{
"key": 3
}],
"bar": [{
"key": 1
},{
"key": 2
},{
"key": 3
}]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment