Are quotes around hash keys a good practice in Perl?

后端 未结 13 2088
伪装坚强ぢ
伪装坚强ぢ 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:16

    I never single-quote hash keys. I know that {} basically works like quotes do, except in special cases (a +, and double-quotes). My editor knows this too, and gives me some color-based cues to make sure that I did what I intended.

    Using single-quotes everywhere seems to me like a "defensive" practice perpetrated by people that don't know Perl. Save some keyboard wear and learn Perl :)

    With the rant out of the way, the real reason I am posting this comment...the other comments seem to have missed the fact that + will "unquote" a bareword. That means you can write:

    sub foo {
        $hash{+shift} = 42;
    }
    

    or:

    use constant foo => 'OH HAI';
    $hash{+foo} = 'I AM A LOLCAT';
    

    So it's pretty clear that +shift means "call the shift function" and shift means "the string 'shift'".

    I will also point out that cperl-mode highlights all of the various cases correctly. If it doesn't, ping me on IRC and I will fix it :)

    (Oh, and one more thing. I do quote attribute names in Moose, as in has 'foo' => .... This is a habit I picked up from working with stevan, and although I think it looks nice... it is a bit inconsistent with the rest of my code. Maybe I will stop doing it soon.)

提交回复
热议问题