On 08/06/2011 13:02, Sayth Renshaw wrote:
Working through the exercises in Learning Perl. Chapter 3 exercise 2.
Basically have to look up a set of names and return an output list of
based on the numbers selected by the user. 1 would print fred etc. For
the longest time I had the below code but couldn't figure out the body
of the foreach loop so I reviewed the appendix at it supplied the
answer as print "$mynames[ $_ - 1 ]\n";
However I keep receiving the following error when attempting to use this script.
This is the code:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @mynames = qw/fred betty barney dino wilma pebbles bamm-bamm/;
print " Enter a number from 1 to 7: ";
chomp(my @nums =<STDIN>);
foreach (@nums) {
print "$mynames[ $_ - 1 ]\n";
}
The error:
C:\MyPerl>perl ch3_2.pl
Enter a number from 1 to 7: 2
^Z
Use of uninitialized value $mynames in concatenation (.) or string at ch3_2.pl l
ine 11,<STDIN> line 1.
[ 2 -1 ]
C:\MyPerl>
Any idea where it comes from?
That looks fine, but Perl is trying to interpolate $mynames (which
hasn't been initalised) into the string instead of indexing an element
of @mynames.
You may be running an old perl. Please check your version with
perl -v
and, in the mean time, fix your program by changing the print statement
to
print $mynames[$_-1], "\n";
HTH,
Rob
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/