%temp = %$value;
how can i make this work (dont work)
$certname = $value->{'certname'};
$temp{$certname} = %$value;
i lose the %$value | [reply] [d/l] [select] |
how can i make this work (dont work)
Individual hash (and array) elements must be scalars. In order to store a more complex data structure, you have to store a reference — which is what $value already is. So assuming that this is what you want to do, and assuming %temp was previously declared as a hash,
$certname = $value->{'certname'};
$temp{$certname} = $value;
should do the trick.
| [reply] [d/l] |
Building on AppleFritter's answers:
You can combine the loop through your results with the hash-building using map, which transforms one list into another, while performing some action on each element. In this case the action would be to add the appropriate key and value to your hash. (And we can transform the first list into a hash because a hash is a list of pairs ...)
my %json_hash = however_you_got_it();
my %new_hash = map { $_->{'certname'} => $_ } values %{ $json_hash{'r
+esults'} };
Here map takes each element of the list returned by values(), which is a hashref, extracts the value of its key 'certname', uses that as the key in the new hash, and uses the entire hashref as the value.
Also note that I dereferenced the hashref $json_hash{'results'} before using it, because it's not "stable" Perl code to call values() (or keys()) on a hashref. I imagine you got a warning like "values on reference is experimental at ...", no?
Hope this helps!
The way forward always starts with a minimal test.
| [reply] [d/l] [select] |
Also note that I dereferenced the hashref $json_hash{'results'} before using it, because it's not "stable" Perl code to call values() (or keys()) on a hashref. I imagine you got a warning like "values on reference is experimental at ...", no?
More than that, I seem to recall that this either already is deprecated and scheduled to be removed (though I can't find it in perldeprecation perldeprecation), or that deprecation was at the very least discussed. Warning or not I'd definitely not use keys and friends on a reference.
EDIT: found it. It's been removed in Perl 5.24; see perl5240delta.
| [reply] |
just added the'\' and worked :)
foreach my $value (values $jsonhash{results} )
{
$temp{$value->{'certname'}} = \%$value;
}
| [reply] [d/l] |
That works, but it is unnecessary, since \ and % are complements, in a sense, and cancel each other out: % dereferences a hash reference ($value), i.e. gives you the hash it references; \ then gives you a reference to this hash again.
There's nothing wrong with doing it this way, but I encourage you to get a good grip on references (hash or not). You'll often encounter them in Perl, and nested data structures don't work without them at all.
| [reply] |
| [reply] [d/l] [select] |