Home arrow Perl Programming arrow Page 7 - Perl 101 (Part 3) - Looping The Loop

Grade School - Perl

Part 3 in our continuing series on the popular scripting language, Perl. This week's article teaches you more about Perl's controlstructures - including the FOR and WHILE loops - and also introduces you toPerl's array variables.

  1. Perl 101 (Part 3) - Looping The Loop
  2. While You Were Sleeping...
  3. ...Or Until You Wake Up
  4. Dos And Don'ts
  5. For Pete's Sake!
  6. Every Comedian Needs An Exit
  7. Grade School
  8. Playing With Friends
  9. So Many Choices...
By: Vikram Vaswani and Harish Kamath, (c) Melonfire
Rating: starstarstarstarstar / 5
June 15, 2000

print this article


Before we go on to our last - also known as final - control structure ofthe day, we're going to take a quick detour and introduce you to adifferent kind of variable.

As you already know, Perl comes with scalar variables, which can be used tostore a single value. But what you may not know is that it also comes witha mechanism to store multiple values in a single variable. This variable isknown as an "array variable", and it is a useful method of storing andrepresenting related information.

All the standard rules which apply when naming scalar variables also applyin the case of array variables, with one important exception - where ascalar variable name is preceded by a dollar [$] sign, an array variablename is preceded by an @ symbol.

Note also that Perl does not place any restrictions on array and scalarvariables sharing the same name in Perl - so the array @stuff is differentfrom the scalar $stuff.

Now, let's say that you wanted to create an array containing the names ofyour friends:

@friends = ("Rachel", "Monica", "Phoebe", "Chandler", "Joey", "Ross");
Thus the array variable @friends contains six elements.

Each element of the array is a scalar variable, and can be accessed usingscalar notation, with a suffix denoting the element's position in thearray. So, in order to extract the first element of the array @friends,you'd use


would give you the sixth element of the array, Ross.

Similarly, if you wanted to modify a particular element of the array, youcould use the scalar notation above to accomplish your task, like this:

$friends[3] = "Janice";
Your array would now contain

("Rachel", "Monica", "Phoebe", "Janice", "Joey", "Ross");
Note that the first element of an array is always referred to by the index0 - this concept, known as "zero-based indexing" often confuses noviceprogrammers, and is just one more reason why geeks have so few friends.

An array can contain both string and numeric data - for example, this isperfectly valid:

@mix = ("hello", 34747, 3, "bonjour");
How about a quick example to illustrate how data can be stored in a singlearray variable:

#!/usr/bin/perl # this example demonstrates how a single # array variable can hold a student's gradea # in six subjects # set up some variables @subjectlist = ("Math", "Lit.", "Physics", "Biology"); @gradelist = (); $total = 0; # get and store input for($x=0; $x<4; $x++) { print("What was your grade in $subjectlist[$x]? "); $gradelist[$x] = <STDIN>; chomp($gradelist[$x]); } # display it in neatly formatted rows print ("SUBJECT\t\tGRADE\n"); for($y=0; $y<4; $y++) { print ("$subjectlist[$y]\t\t$gradelist[$y]\n"); $total += $gradelist[$y]; } # print a total print ("TOTAL: $total\n");
And here's what it looks like:

What was your grade in Math? 10 What was your grade in Lit.? 20 What was your grade in Physics? 30 What was your grade in Biology? 40 SUBJECT GRADE Math 10 Lit. 20 Physics 30 Biology 40 TOTAL: 100
Let's walk you through this: we've begun by initializing two arrayvariables and one scalar variable. The array @subjectlist contains a listof the subjects to be graded, and the array @gradelist will be populated bythe user with the actual grades. The scalar variable $total will be used todisplay a total figure at the end.

Next, we've used a "for" loop to display a question, and assign the user'sinput to the @gradelist array in the appropriate slot via the $x counter.Once all four subjects are taken care of [note the conditional expressionin the "for" loop, which automatically stops looping when the counterreaches 4], we've simply used the print() function and a second "for" loopto display a neatly-tabulated row of grades and subjects.

The second loop also adds each grade to the variable $total, and thisdisplays this total value at the end of the program.

A couple of other points to note:

* The \t character used in the print() statements above is used to generatea single "tab" space.

* The notation

$total += $gradelist[$y];

is simply a Perl shortcut for

$total = $total + $gradelist[$y];

This article copyright Melonfire 2000. All rights reserved.

>>> More Perl Programming Articles          >>> More By Vikram Vaswani and Harish Kamath, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: