我在 Perl 中遇到了一个奇怪的行为,我无法找到相关文档。如果我(偶然)使用字符串作为数组中的索引,我会得到数组的第一项,而不是undef我所期望的。
$index = "Some string";
@array = qw(one two three);
$item = $array[$index];
print "item: " . $item;
Run Code Online (Sandbox Code Playgroud)
我期望得到item: 输出,但我得到的是item: one. 我假设因为字符串不是以数字开头,所以它被“翻译”为 0,从而给我数组中的第一项。如果字符串以数字开头,则字符串的该部分似乎用作索引。
这是预期的吗?是否有任何文档描述如何"2strings"在 Perl 中将字符串(例如)解释为数字?
数组索引强加数字上下文。数字上下文中的字符串“Some string”等于 0。
在警告下,Perl会抱怨
Argument "Some string" isn't numeric in array or hash lookup at ...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
557 次 |
| 最近记录: |