Indexing perl array

I have below code

@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");

Output seen:

Position is kaje
Next is beje
Array of c is danjo
Array at m is kaje

I want to understand how this works. Here $next is the matched string and i am able to index on that string for given array. Also $m is not found in the array, yet we get output as first element of array.


Solution 1:

ALWAYS use use strict; use warnings;. It answers your question.

In one place, you treat the string kaje as a number.

In two places, you treat the string kajes as a number.

Since these two strings aren't numbers, Perl will use zero and issue a warning.

In other words, Next is beje only "works" because kaje happens to be at index 0. I have no idea how why you believe the last two lines work seeing as kajes is nowhere in the array.


You want

# Find the index of the element with value `kaje`.
my ($i) = grep $ar1[$_] eq 'kaje', 0..$#ar1;