Perl 中围绕散列键的引号是一个好习惯吗?

发布于 2024-07-11 18:39:41 字数 796 浏览 5 评论 0原文

在 Perl 中使用散列时引用键是个好主意吗?

我正在开发一个非常大的遗留 Perl 代码库,并尝试采用 Damian Conway 在 中建议的许多最佳实践Perl 最佳实践。 我知道最佳实践始终对于程序员来说是一个敏感的话题,但希望我能在这个问题上得到一些好的答案,而不会引发一场激烈的争论。 我也知道,这可能是很多人不会争论的事情,因为它是一个小问题,但在我处理这个代码库时,我试图获得一份可靠的指南列表来遵循。

Damian Conway 所著的《Perl 最佳实践》一书中,有一个示例展示了对齐如何帮助代码部分,但它没有提到(在我能找到的书中的任何地方)任何有关引用哈希键的内容。

$ident{ name   } = standardize_name($name);
$ident{ age    } = time - $birth_date;
$ident{ status } = 'active';

用引号来强调你没有使用裸词不是更好吗?

$ident{ 'name'   } = standardize_name($name);
$ident{ 'age'    } = time - $birth_date;
$ident{ 'status' } = 'active';

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';

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

糖粟与秋泊 2024-07-18 18:39:41

指定常量字符串哈希键时,应始终使用(单)引号。 例如,$hash{'key'} 这是最好的选择,因为它无需考虑此问题并可实现一致的格式。 如果您有时省略引号,则当您的密钥包含内部连字符、空格或其他特殊字符时,您必须记住添加它们。 在这些情况下,您必须使用引号,从而导致格式不一致(有时不加引号,有时加引号)。 引用的键也更有可能被编辑器语法突出显示。

下面是一个示例,其中使用“有时引用,其他时候不引用”约定可能会给您带来麻烦:

$settings{unlink-devices} = 1; # I saved two characters!

use strict 下编译得很好,但在运行时不会完全达到您的预期。 哈希键是字符串。 字符串应根据其内容使用适当的引号:单引号表示文字字符串,双引号允许变量插值。 引用您的哈希键。 这是最安全的约定,也是最容易理解和遵循的约定。

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:

$settings{unlink-devices} = 1; # I saved two characters!

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.

放飞的风筝 2024-07-18 18:39:41

不带引号更好。 它位于 {} 中,因此很明显您没有使用裸字,而且它更易于阅读和输入(少了两个符号)。 但当然,所有这一切都取决于程序员。

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.

天暗了我发光 2024-07-18 18:39:41

我从不单引号哈希键。 我知道 {} 基本上像引号一样工作,除了特殊情况(+ 和双引号)。 我的编辑也知道这一点,并给了我一些基于颜色的提示,以确保我做了我想要的事情。

在我看来,到处使用单引号就像不懂 Perl 的人所做的一种“防御”做法。 节省一些键盘磨损并学习 Perl :)

随着咆哮的出现,我发布此评论的真正原因...其他评论似乎忽略了 + 将“取消引用”的事实一个裸词。 这意味着你可以写:

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

或:

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

所以很明显,+shift 表示“调用sh​​ift 函数”,而shift 表示“字符串'shift'”。

我还将指出 cperl 模式正确地突出显示了所有不同的情况。 如果没有,请在 IRC 上 ping 我,我会修复它:)

(哦,还有一件事。我在 Moose 中引用了属性名称,如 has 'foo' => ...

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.)

今天小雨转甜 2024-07-18 18:39:41

Larry Wall 对无引号哈希键进行了语法级别的关注,以确保它们没有理由不采用最佳实践。 不要担心引号。

(顺便说一句,数组键上的引号 PHP 中的最佳实践,如果不使用它们可能会产生严重后果,更不用说大量的 E_WARNING。在 Perl 中好!= PHP 中好。)

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.)

千秋岁 2024-07-18 18:39:41

我认为这方面没有最佳实践。 就我个人而言,我在哈希键中使用它们,如下所示:

$ident{'name'} = standardize_name($name);

但不要在箭头运算符的左侧使用它们:

$ident = {name => standardize_name($name)};

不要问我为什么,这只是我这样做的方式:)

我认为你能做的最重要的事情是总是,总是,总是:

use strict;
use warnings; 

这样,编译器将为您捕获任何语义错误,使您不太可能输错某些内容,无论您决定采用哪种方式。

第二个最重要的事情是保持一致。

I don't think there's a best practice on this one. Personally I use them in hash keys like so:

$ident{'name'} = standardize_name($name);

but don't use them to the left of the arrow operator:

$ident = {name => standardize_name($name)};

Don't ask me why, it's just the way I do it :)

I think the most important thing you can do is to always, always, always:

use strict;
use warnings; 

That way the compiler will catch any semantic errors for you, leaving you less likely to mistype something, whichever way you decide to go.

And the second most important thing is to be consistent.

独留℉清风醉 2024-07-18 18:39:41

我不加引号,只是因为这样可以减少打字、阅读和担心。 我有一个不会被自动引用的密钥的时候很少而且间隔很远,因此不值得所有额外的工作和混乱。 也许我对哈希键的选择已经改变以适应我的风格,这也没关系。 完全避免边缘情况。

这与我默认使用 " 的原因是一样的。对我来说,在字符串中间放置一个变量比使用我不想插入的字符更常见。这是也就是说,我更常写'你好,我的名字是$name',而不是“你欠我1000美元”

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".

貪欢 2024-07-18 18:39:41

至少,引用可以防止在不太完美的编辑器中语法突出显示保留字。 查看:

$i{keys} = $a;
$i{values} = [1,2];
...

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

$i{keys} = $a;
$i{values} = [1,2];
...
零度℉ 2024-07-18 18:39:41

我更喜欢不带引号,除非我想要一些字符串插值。 然后我使用双引号。 我把它比作文字数字。 Perl 确实允许您执行以下操作:

$achoo['1']  = 'kleenex';
$achoo['14'] = 'hankies';

但没有人这样做。 这对清晰度没有帮助,只是因为我们添加了两个更多的字符来输入。 就像有时我们特别希望数组中的槽 #3 一样,有时我们希望 PATH 条目位于 %ENV 之外。 就我而言,单引号不会增加清晰度。

Perl 解析代码的方式使得不可能在哈希索引中使用其他类型的“裸词”。

尝试一下

$myhash{shift}

,您只会获取存储在 'shift' 键下的哈希中的项目,您必须执行此操作

$myhash{shift()}

才能指定您希望第一个参数为哈希建立索引。

此外,我使用jEdit唯一可视化编辑器(我见过- -除了 emacs 之外),允许您完全控制突出显示。 所以这对我来说是双重清楚的。 任何看起来像前者的东西都会得到 KEYWORD3 ($myhash) + SYMBOL ({) + LITERAL2 (shift) + SYMBOL (}) 如果在结束花之前有一个括号,它会得到 KEYWORD3 + SYMBOL + KEYWORD1 + SYMBOL (()})。 另外,我可能也会将其格式化为这样:

$myhash{ shift() }

I prefer to go without quotes, unless I want some string interpolation. And then I use double quotes. I liken it to literal numbers. Perl would really allow you to do the following:

$achoo['1']  = 'kleenex';
$achoo['14'] = 'hankies';

But nobody does that. And it doesn't help with clarity, simply because we add two more characters to type. Just like sometimes we specifically want slot #3 in an array, sometimes we want the PATH entry out of %ENV. Single-quoting it add no clarity as far as I'm concerned.

The way Perl parses code makes it impossible to use other types of "bare words" in a hash index.

Try

$myhash{shift}

and you're only going to get the item stored in the hash under the 'shift' key, you have to do this

$myhash{shift()}

in order to specify that you want the first argument to index your hash.

In addition, I use jEdit, the ONLY visual editor (that I've seen--besides emacs) that allows you total control over highlighting. So it's doubly clear to me. Anything looking like the former gets KEYWORD3 ($myhash) + SYMBOL ({) + LITERAL2 (shift) + SYMBOL (}) if there is a paranthesis before the closing curly it gets KEYWORD3 + SYMBOL + KEYWORD1 + SYMBOL (()}). Plus I'll likely format it like this as well:

$myhash{ shift() }
撧情箌佬 2024-07-18 18:39:41

跟着引号走吧! 它们在视觉上打破了语法,更多的编辑器将在语法突出显示中支持它们(嘿,甚至 Stack Overflow 也在突出显示引用版本)。 我还认为,通过编辑检查您是否结束了引用,您会更快地注意到拼写错误。

Go with the quotes! They visually break up the syntax and more editors will support them in the syntax highlighting (hey, even Stack Overflow is highlighting the quote version). I'd also argue that you'd notice typos quicker with editors checking that you ended your quote.

雨落星ぅ辰 2024-07-18 18:39:41

最好使用引号,因为它允许您使用裸词中不允许的特殊字符。 通过使用引号,我可以在哈希键中使用我的母语的特殊字符。

It is better with quotes because it allows you to use special characters not permitted in barewords. By using quotes I can use the special characters of my mother tongue in hash keys.

入怼 2024-07-18 18:39:41

我自己也想知道这一点,尤其是当我发现自己犯了一些错误时:

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

我现在倾向于做的是,如果至少一个文字键需要引号,则在每个哈希的基础上普遍应用引号; 并使用括号和常量:

 $hash{CONSTANT()} = 'ugly, but what can you do?';

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?';
遮了一弯 2024-07-18 18:39:41

您也可以在键前添加“-”(减号字符),但请注意,这会将“-”附加到开头你的钥匙。 从我的一些代码来看:

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

我也使用单引号、双引号和无引号方式。 全部在同一个程序中:-)

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 :-)

我做我的改变 2024-07-18 18:39:41

我总是在不带引号的情况下使用它们,但我会赞同使用严格和警告,因为它们指出了大多数常见错误。

I've always used them without quotes but I would echo the use of strict and warnings as they pick out most of the common mistakes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文