| |||||||||||
| |||||||||||
Aaaaaaargh! I am losing my head! Posted by karthikshenoy (karthikshenoy), 17 June 2003 I would like to sum up the marks of each individual in the following two-dimensional (though not really 2 dimensional) array.@gradebook = ( ["Mary", 100, 94, 98, 42], ["John", 90, 64, 78, 56], ["Joan", 80, 94, 38, 72], ["Bill", 18, 64, 81, 98], ["Bret", 60, 74, 87, 23] ); for $x (0 .. $#gradebook) { for $y (1 .. $#{gradebook[$x]} ) { $sum += $gradebook[$x][$y]; } print "$sum . \n"; $sum = 0; } I get a syntax error near "$#{gradebook[" in the nested for loop. Can anyone tell me what the problem is? I have two further queries: 1. How come the keyword "for" is being used here without following the normal syntax which is: for(Initial_Statement; expression; Increment_Statement){} 2. Why is "$#gradebook" being used to find out the length of one of the dimensions when "$gradebook" should actually suffice? I am new to Perl. Please excuse me if some of the above queries are trivial. Thanks in advance! Posted by admin (Graham Ellis), 17 June 2003 You need an extra $ ... the line that's failing should read:for $y (1 .. $#{$gradebook[$x]} ) { Answering your extra questions: 1. The for loop has two different syntaxes - the one that you've used in this program where the brackets contain a list, and the other one where the brackets contain three expressions separated by semicolons. Perl decides which way to iterate the loop depending on whether or not there are two semicolons present. You'll often find the word foreach used in place of for in the syntax without semicolons, but in fact the two words are synonyms and you can use either. 2. $gradebook would be a scalar that's nothing to do with the list @gradebook. $#gradebook is different - it is the index number of the last element of the list. It would make for hard-to-read code, but you could in theory have a list, a hash, a scalar, a subroutine and a file handle all called "gradebook" - Perl is perfectly able to work out which is which in the code, even if it's much harder for the human reader / code maintainer! Posted by karthikshenoy (karthikshenoy), 17 June 2003 Thanks Graham!I appreciate the effort you are taking to reply ![]() This page is a thread posted to the opentalk forum
at www.opentalk.org.uk and
archived here for reference. To jump to the archive index please
follow this link.
|
| ||||||||||
PH: 01144 1225 708225 • FAX: 01144 1225 793803 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho |