Perl arrays: referencing with the dollar sign

Tutoring computer science, small details can be very meaningful.  The tutor brings up an important one about Perl array referencing.

 
Back in my Oct 4 post, I introduced a Perl program that searches a grocery list for olive oil. The items in the list are stored in an array; the program checks the items one by one to see if that particular item is olive oil.

A point is that while the array is called @groceries, a single element in the array is referenced using $groceries[index]. For example, the zeroth element is referenced by $groceries[0]. The dollar sign is used to reference a single element in the array.

Another point, which is just a reminder, is that Perl arrays start at position 0. Therefore, the third element in @groceries is $groceries[2]. Perl sees it as $groceries[0], $groceries[1], $groceries[2]….

My compiler seems rather relaxed about whether I use $groceries[2] or @groceries[2] to reference the third element in the array. However, everywhere I read says to reference a single array element with $array[index] rather than @array[index]; I guess we will.

HTH & HNY:)

Sources:

Robert’s Perl tutorial

McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply