3.1. Accessing Elements of an Array
If you've used arrays in another language, you won't be surprised to find Perl provides a way to subscript an array to refer to an element by a numeric index.
$fred = "yabba"; $fred = "dabba"; $fred = "doo";
The array name (in this case, "fred") is from a completely separate namespace than scalars use. You could have a scalar variable named $fred in the same program. Perl treats them as different things and doesn't get confused.[*] (Your maintenance programmer might be confused though, so don't capriciously make all of your variable names the same.)
You can use an array element like $fred in every place where you could use any other scalar variable like $fred. For example, you can get the value from an array element or change that value by the same sorts of expressions we used in the previous chapter:
print $fred; $fred = "diddley"; $fred .= "whatsis";
Of course, the subscript may be any expression that gives a numeric value. If it's not an integer, it'll automatically be truncated to the next lower integer:
$number = 2.71828; print $fred[$number - 1]; # Same as printing $fred
If the subscript indicates an element that would be beyond the end of the array, the corresponding value will be undef. This is the same as ordinary scalars; if you've never stored a value into the variable, it's undef.
$blank = $fred[ 142_857 ]; # unused array element gives undef $blanc = $mel; # unused scalar $mel also gives undef