huang cheng
huang cheng

Reputation: 393

Perl : $_ and $array[$_] issue

Below is my code , please review.

use strict;
my @people = qw{a b c d e f};
foreach (@people){
    print $_,"$people[$_]\n";
}

Below is the output,

[~/perl]$ perl test.pl
aa             #why the output of $people[$_] is not same with $_?
ba
ca
da
ea
fa

Thanks for your asking.

Upvotes: 1

Views: 122

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70307

$_ is the actual element you're looking at. $people[$_] is getting the $_th element out of @people. It's intended to be used with numerical indices, so it numifies its argument. Taking a letter and "converting" it to a number just converts to zero since it can't parse a number out of it. So $people[$_] is just $people[0] when $_ is not a number. If you try the same experiment where some of the list elements are actually numerical, you'll get some more interesting results.

Try:

use strict;
my @people = qw{a b c 3 2 1};
foreach (@people){
    print $_,"$people[$_]\n";
}

Output:

aa
ba
ca
33
2c
1b

Since, in the first three cases, we couldn't parse a, b, or c as numbers so we got the zeroth element. Then, we can actually convert 3, 2, and 1 to numbers, so we get elements 3, 2, and then 1.

EDIT: As mentioned in a comment by @ikegami, put use warnings at the top of your file in addition to use strict to get warned about this sort of thing.

Upvotes: 8

Related Questions