This is actually pretty close to what you wanted. Un-comment use warnings and the resulting message will help to identify the problem:
Use of uninitialized value in concatenation (.) or string at first.pl
+line 5.
The problem loop is:
foreach my $num (@arr) {
print "Index is: $num. Value is: $arr[$num] ";
}
and as the output shows, the loop value is always one greater than the index. That’s because arrays in Perl (as in C) are subscripted starting from zero, so $arr[1] is actually the second element. The loop is easily fixed:
foreach my $num (@arr) {
print "Index is: $num. Value is: $arr[$num - 1] "; # Subtra
+ct 1 from the index
}
Also un-comment use strict, and you’ll see that the only error message pertains to this line:
for($num = 0; $num<= $#arr;$num++) {
Declare $num as a lexical variable:
for (my $num = 0; ...
and strict is happy.
Hope that helps,
|