Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`$_` variable giving incorrect output

Tags:

perl

If I do

my @answer = qw(java python perl c);
foreach (@answer){
          print "[$_]\n";
}

then it will print

[java]
[python]
[perl]
[c]


But, if I add $answer before [$_]:

my @answer = qw(java python perl c);
foreach (@answer){
       print "$answer[$_]\n";
}

then it will print

java java java java


Why is that?

like image 353
Noobs Avatar asked Jul 18 '26 08:07

Noobs


1 Answers

Each element in the loop is put into $_. When you say $answer[$_], you're asking for the array element $answer['java'], $answer['python'], and so on. These strings turn into 0 in numeric context, and therefore what you get is $answer[0], which is java.

like image 78
friedo Avatar answered Jul 21 '26 02:07

friedo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!