Is it a good idea to quote keys when using a hash in Perl?
I am working on an extremely large legacy Perl code base and trying to adopt a lot of the best practices suggested by Damian Conway in Perl Best Practices. I know that best practices are always a touchy subject with programmers, but hopefully I can get some good answers on this one without starting a flame war. I also know that this is probably something that a lot of people wouldn’t argue over due to it being a minor issue, but I’m trying to get a solid list of guidelines to follow as I work my way through this code base.
In the Perl Best Practices book by Damian Conway, there is this example which shows how alignment helps legibility of a section of code, but it doesn’t mention (anywhere in the book that I can find) anything about quoting the hash keys.
$ident{ name } = standardize_name($name); $ident{ age } = time - $birth_date; $ident{ status } = 'active';
Wouldn’t this be better written with quotes to emphasize that you are not using bare words?
$ident{ 'name' } = standardize_name($name); $ident{ 'age' } = time - $birth_date; $ident{ 'status' } = 'active';
When specifying constant string hash keys, you should always use (single) quotes. E.g.,
$hash{'key'}This is the best choice because it obviates the need to think about this issue and results in consistent formatting. If you leave off the quotes sometimes, you have to remember to add them when your key contains internal hypens, spaces, or other special characters. You must use quotes in those cases, leading to inconsistent formatting (sometimes unquoted, sometimes quoted). Quoted keys are also more likely to be syntax-highlighted by your editor.Here’s an example where using the ‘quoted sometimes, not quoted other times’ convention can get you into trouble:
That’ll compile just fine under
use strict, but won’t quite do what you expect at runtime. Hash keys are strings. Strings should be quoted as appropriate for their content: single quotes for literal strings, double quotes to allow variable interpolation. Quote your hash keys. It’s the safest convention and the simplest to understand and follow.