|
|
|
|
|
by DougWebb
3151 days ago
|
|
Why would there be a warning? Your example does exactly what autovivification is supposed to do. Obviously you don't normally use it as obscurely as you've done here. I hate C#'s way of assigning a value to a dictionary, without autovivification: if (dict.ContainsKey("yes"))
{
dict["yes"] = val;
}
else
{
dict.Add("yes", val);
}
You also have to use ContainsKey before you try to use [] to retrieve a value, because [] throws an exception if the key doesn't exist in the dictionary. Perl's autovivification, which assumes you know what you're doing and expect the key to be there when you ask for the value rather than explicity check for the key, makes much more sense and is a lot easier to work with. |
|
This is exactly my point, there should be no autovivification - I'd wager most people using perl these days don't know what they're doing, they're reluctantly editing some legacy code.
It's a dangerous default behaviour that can lead to very hard to debug errors. Most languages don't do this so people don't expect it; I don't know C# but can immediately tell what the code you wrote is doing. Explicit is better.
It's extra confusing because if you try and dereference undef without accessing a value it's an error:
What harm is there in a warning? You can disable classes of warnings in perl if you want to, or turn them off completely. I would much rather be explicit so I don't accidentally use some magic.