1

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.

1
  • 3
    ALWAYS use use strict; use warnings;. It would answer you question Commented Jan 18, 2022 at 5:10

1 Answer 1

7

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.