@Ken: I think you are right - it's time to look at JSON and SQL.
Today I've found the time to hack together a simple test script that doesn't exhibit the original problem. Here, when the variable is properly declared (or not) and populated in perl context, shorthand and longform behave the same.
Also, I've removed the noise of the eval and the defined() check, the latter I threw in anyway down the road when the simple check didn't seem to suffice.
In my production code the related_files data comes from a SQL field that is parsed based on the test
if($sql->{field}), so I think that there's a slight difference how perl regards this field as
defined, existing or true. But I am not so inclined to find out why exactly the shorthand doesn't work. As the more verbose code just works. Also, might also be an unrelated error I am overseeing. I'll post if there's a find in the future.
#! perl
use Data::Dumper;
use JSON::XS;
my $asset = {
## rename this var to something else to test the 'undefined' c
+ase
related_files => '{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
}'
};
my $ref;
if($asset->{related_files}){
$ref = decode_json($asset->{related_files});
}else{
$ref = [];
}
print Dumper($ref);
## simpler shorthand-code doesn't work, why?
my $ref = $asset->{related_files} ? decode_json($asset->{related_files
+}) : [];
print Dumper($ref);
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.