gpt4 book ai didi

perl - 在 Perl 中使用字符串作为数组索引

转载 作者:行者123 更新时间:2023-12-05 00:51:36 25 4
gpt4 key购买 nike

我在 Perl 中遇到了一个我无法找到相关文档的奇怪行为。如果我(偶然)使用字符串作为数组中的索引,我会得到数组的第一项,而不是 undef ,正如我所期望的那样。

$index = "Some string";
@array = qw(one two three);
$item = $array[$index];
print "item: " . $item;

我希望得到 item: 作为输出,但我得到的是 item: one。我假设因为字符串不是以数字开头,所以它被“翻译”为 0,因此给了我数组中的第一项。如果字符串以数字开头,那部分字符串似乎被用作索引。

这是意料之中的吗,是否有任何文档描述了字符串(例如 "2strings")如何在 Perl 中被解释为数字?

最佳答案

数组索引强加数字上下文。数字上下文中的字符串“Some string”等于 0。

warnings 下, Perl 会提示

Argument "Some string" isn't numeric in array or hash lookup at ...

关于perl - 在 Perl 中使用字符串作为数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71592491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com