Slide 6.b: Variables and strings
Slide 6.d: Using Perl to access a MySQL database
Home

Arrays


An array stores a list of values. While a scalar variable can only store one value, an array can store many. Array names are prefixed with an at-sign ‘@’.



 @animals = ("", "", "");
 print  "The animal \$animals[] is $animals[].";
The foreach loop iterates over a normal array value and sets the variable VAR to be each element of the array in turn. The variable is implicitly local to the loop, and regains its former value upon exiting the loop.



 @animals = ("", "", "");
 foreach  $i  (@animals)  {
    print  "The animal is $i.<br>";
 }
An associative array consists of pairs of elements: a key and a data value. The name of an associative array is prefixed with a percent sign (%).



 %URLs = ( "", "",
           "", "",
           "", "" );
 print  "The URL of \$URLs{} is $URLs{}.";
 print  "The URL of \$URLs{''} is $URLs{''}.";
 print  "The URL of \$URLs{\"\"} is $URLs{\"\"}.";
The function keys returns a normal array consisting of all the keys of the named associative array. The keys are returned in a random order.



 %URLs = ( "", "",
           "", "",
           "", "" );
 foreach   $key  (keys %URLs)  {
    print  "The value of $key is $URLs{$key}<br>";
 }