develooper Front page | perl.beginners | Postings from June 2003

Array Question (Learning Perl/Win32 Chapter Test Question)

Thread Next
From:
Anthony Beaman
Date:
June 20, 2003 08:54
Subject:
Array Question (Learning Perl/Win32 Chapter Test Question)
Message ID:
B46773BE879E6D449E7AA93BEC10A44701E83C5C@exchange1.trghd.com
Hi! Arrays are confusing me and I don't know why. I feel that I understand it but the test questions in Learning Perl for Win32 is tripping me up. For example, here's #2 below with the answer and explanation:

2. Write a program that reads a number and then a list of strings (all on separate lines), and then prints one of the lines from the list as selected by the number.

One way to do this is:
print "Enter the line number: "; chomp($a = <STDIN>);
 print "Enter the lines, end with ^Z:\n"; @b = <STDIN>;
 print "Answer: $b[$a-1]";
The first line prompts for a number, reads it from standard input, and removes that pesky newline. The second line asks for a list of strings, then uses the <STDIN> operator in a list context to read all of the lines until end-of-file into an array variable. The final statement prints the answer, using an array reference to select the proper line. Note that we don't have to add a newline to the end of this string, because the line selected from the @b array still has its newline ending. You'll need to type CTRL-Z at the console to indicate an end-of-file.
 
I'm confused on the [$a-1] part of the last line. Why not $b[$a] instead? Also, are there any notes online for this book or summaries? I've made notes from the book but I'm still not able to compartmentalize how to use arrays (I feel that I do but I'm getting screwed by these test questions!! I've moved on to other chapters but they're nailing me also. ARGH!!!). Thanks! :-)


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About