in reply to Defined test creates non-empty hash value

There is more discussion about this here: https://www.perlmonks.org/?node_id=11151225 as this also caught me out.

Most languages don't have autovivication which I think is why it catches so many people. My general thoughts on this is autovivication is overall more useful.

Example: If you have a JSON structure in an object and you want to check if a certain item in the structure exists with a value, in javascript to avoid throwing an error it is extremely annoying:

if (json && json.command && json.command.results && json.command.results[0] && json.command.results[0].code && (json.command.results[0].code == 9))

But in perl with autovivificatin, its much nicer:

if ($json->{command}{results}[0]{code}//0 == 9)

Replies are listed 'Best First'.
Re^2: Defined test creates non-empty hash value
by etj (Priest) on Jun 17, 2024 at 13:58 UTC
    ...unless you didn't want to create the deeper structure. It's a bit swings and roundabouts!