Now I need to get {"teams":[1, 2, 35]}
, I wrote below code.
use JSON
my @array;
@array=(1, 2, 35);
my %hash;
$hash{"teams"}=@array;
$json = encode_json(\%hash);
print $json."\n";
but I just get {"teams":3}
.
My question is can array be value of Hash in Perl?
答案 0 :(得分:12)
Yes, it can.
In perl
multi-dimensional structures are done via references:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
my @array;
@array=(1, 2, 35);
my %hash;
$hash{"teams"}=\@array;
my $json = encode_json(\%hash);
print $json."\n";
The way this works is - your hash value can only be single scalar value. This should be a reference to an array.
This prints:
{"teams":[1,2,35]}
You could accomplish the same result with:
$hash{"teams"}=[@array];
Which is similar, in that it copies @array
into an anonymous array.
The distinction comes if you re-use @array
:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
my @array;
@array=(1, 2, 35);
my %hash;
$hash{"teams"}=\@array;
@array = ( 3, 4, 5 ) ;
$hash{"more"} = \@array;
my $json = encode_json(\%hash);
print $json."\n";
This will actually print:
{"teams":[3,4,5],"more":[3,4,5]}
Because you've altered the array, and used a reference to the same array twice.
But if you do:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
my @array;
@array=(1, 2, 35);
my %hash;
$hash{"teams"}=[@array];
@array = ( 3, 4, 5 ) ;
$hash{"more"} = [@array];
my $json = encode_json(\%hash);
print $json."\n";
You get:
{"more":[3,4,5],"teams":[1,2,35]}
You can see what's going on with the rather handy Data::Dumper
module:
#!/usr/bin/env perl
use strict;
use warnings;
use JSON;
use Data::Dumper;
my @array;
@array = ( 1, 2, 35 );
my %hash;
$hash{"teams"} = @array;
print Dumper \%hash;
You'll see that what's in hash
is:
$VAR1 = {
'teams' => 3
};
{"teams":3}
Why you might ask? Well, because the entry in a hash can only be a scalar.
So you are accessing your array in a scalar context. And an array in a scalar context, prints it's number of elements:
print scalar @array; # prints 3
Which is what's happening in your example.