in reply to Learning Perl - Question About Using a For Loop To Pull Data From an Array

Hi aUserName,

In addition to what the others have said, I'd strongly recommend you add use strict; in addition to use warnings; at the top of your code. strict enforces a style of coding that is less prone to errors, which can be very helpful when you're learning. It's also a good habit to learn early, in fact, recent versions of Perl turn it on by default when you say use v5.12; (or higher) at the top of your code. warnings will give you warnings that are almost always helpful in tracking down (potential) bugs.

When you first turn on strict, you'll need to change your script so that your variables are declared with my. The page Use strict and warnings explains this.

Another very helpful thing for learning Perl is putting use diagnostics; at the top of your script. diagnostics will expand any error messages you get into longer explanations. I'd also recommend you look at the Basic debugging checklist.

One more thing about your code: When you write @userNumber = <STDIN>;, then each element of @userNumber is a string that still contains the newline "\n" after the number (from pressing Return after each input). Your code works because Perl is silently ignoring that newline when you write $counter-1 and convert the string to a number, but it may cause problems when you do other things with the user input - try changing the print in the loop to print "the name $counter is: $names[$counter-1]\n"; and you'll see the newline as part of the output! That's why there's the helpful function chomp which removes the newlines for you. Either write chomp(@userNumber);, or you can combine the reading with the chomping into the perlish idiom chomp(my @userNumber = <STDIN>);.

Hope this helps,
-- Hauke D