Avoid my keys() accident

I broke $work yesterday when a change I'd made that I thought was mundane was not in fact. I'd changed some code from: if ( keys %$hash_ref ) { to if ( %$hash_ref ) { under the theory that we weren't supporting any perl less than our current production at perl-5.10.0.

What I'd completely missed was that $hash_ref might be undef and that keys %$... would auto-vivify the hash if necessary. Previously, the hash would be created as a side effect of dereferencing it. Afterward, I got an exception because the hash wasn't being automatically created just by looking at it.

The reason for this is keys() is actually an lvalue, something you can assign to. The meaning of keys( %... ) = 8 is actually fairly obscure and not what you would guess if you haven't read the documentation for keys(). Because keys() is an lvalue, the dereference %$... will auto-vivify anything necessary because I might want to modify it.

When I dropped the usage of something strictly defined as an lvalue function, the dereference stopped auto-vivifying and now I had exceptions in production. Wheee!

Leave a comment

About Josh ben Jore

user-pic