Are quotes around hash keys a good practice in Perl?

后端 未结 13 2004
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 06:24

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 s

相关标签:
13条回答
  • 2020-12-03 07:05

    You can precede the key with a "-" (minus character) too, but be aware that this appends the "-" to the beginning of your key. From some of my code:

    $args{-title} ||= "Intrig";
    

    I use the single quote, double quote, and quoteless way too. All in the same program :-)

    0 讨论(0)
  • 2020-12-03 07:08

    Without quotes is better. It's in {} so it's obvious that you are not using barewords, plus it is both easier to read and type (two less symbols). But all of this depends on the programmer, of course.

    0 讨论(0)
  • 2020-12-03 07:09

    I've wondered about this myself, especially when I found I've made some lapses:

     use constant CONSTANT => 'something';
     ...
     my %hash = ()
     $hash{CONSTANT}          = 'whoops!';  # Not what I intended
     $hash{word-with-hyphens} = 'whoops!';  # wrong again 
    

    What I tend to do now is to apply quotes universally on a per-hash basis if at least one of the literal keys needs them; and use parentheses with constants:

     $hash{CONSTANT()} = 'ugly, but what can you do?';
    
    0 讨论(0)
  • 2020-12-03 07:10

    At least, quoting prevent syntax highlighting reserved words in not-so-perfect editors. Check out:

    $i{keys} = $a;
    $i{values} = [1,2];
    ...
    
    0 讨论(0)
  • 2020-12-03 07:12

    I go without quotes, just because it's less to type and read and worry about. The times when I have a key which won't be auto-quoted are few and far between so as not to be worth all the extra work and clutter. Perhaps my choice of hash keys have changed to fit my style, which is just as well. Avoid the edge cases entirely.

    It is sort of the same reason I use " by default. It's more common for me to plop a variable in the middle of a string than to use a character that I don't want interpolated. Which is to say, I've more often written 'Hello, my name is $name' than "You owe me $1000".

    0 讨论(0)
  • 2020-12-03 07:13

    Quoteless hash keys received syntax-level attention from Larry Wall to make sure that there would be no reason for them to be other than best practice. Don't sweat the quotes.

    (Incidentally, quotes on array keys are best practice in PHP, and there can be serious consequences to failing to use them, not to mention tons of E_WARNINGs. Okay in Perl != okay in PHP.)

    0 讨论(0)
提交回复
热议问题