索引 perl 数组
Indexing perl array
我有以下代码
@ar1 = ('kaje','beje','ceje','danjo');
$m = 'kajes';
my($next) = grep $_ eq 'kaje',@ar1;
print("Position is $next\n");
print("Next is $ar1[$next+1]\n");
print("Array of c is $ar1[$m+3]\n");
print("Array at m is $ar1[$m]\n");
看到的输出:
Position is kaje
Next is beje
Array of c is danjo
Array at m is kaje
我想了解这是如何工作的。这里 $next 是匹配的字符串,我能够为给定数组在该字符串上建立索引。同样在数组中找不到 $m,但我们将输出作为数组的第一个元素。
始终使用 use strict; use warnings;
。它回答了你的问题。
在一处,您将字符串 kaje
视为数字。
在两个地方,您将字符串 kajes
视为数字。
由于这两个字符串不是数字,Perl 将使用零并发出警告。
换句话说,Next is beje
仅“有效”,因为 kaje
恰好位于索引 0
。我不知道为什么你认为最后两行有效,因为 kajes
不在数组中。
你想要
# Find the index of the element with value `kaje`.
my ($i) = grep $ar1[$_] eq 'kaje', 0..$#ar1;
我有以下代码
@ar1 = ('kaje','beje','ceje','danjo');
$m = 'kajes';
my($next) = grep $_ eq 'kaje',@ar1;
print("Position is $next\n");
print("Next is $ar1[$next+1]\n");
print("Array of c is $ar1[$m+3]\n");
print("Array at m is $ar1[$m]\n");
看到的输出:
Position is kaje
Next is beje
Array of c is danjo
Array at m is kaje
我想了解这是如何工作的。这里 $next 是匹配的字符串,我能够为给定数组在该字符串上建立索引。同样在数组中找不到 $m,但我们将输出作为数组的第一个元素。
始终使用 use strict; use warnings;
。它回答了你的问题。
在一处,您将字符串 kaje
视为数字。
在两个地方,您将字符串 kajes
视为数字。
由于这两个字符串不是数字,Perl 将使用零并发出警告。
换句话说,Next is beje
仅“有效”,因为 kaje
恰好位于索引 0
。我不知道为什么你认为最后两行有效,因为 kajes
不在数组中。
你想要
# Find the index of the element with value `kaje`.
my ($i) = grep $ar1[$_] eq 'kaje', 0..$#ar1;