Accessing Elements of an Array

If you've used arrays in another programming language, you won't be surprised to find that Perl provides a way to subscript an array in order to refer to an element by a numeric index.

The array elements are numbered using sequential integers, beginning at zero and increasing by one for each element, like this:

	$fred[0] = 'yabba";
	$fred[1] = 'dabba";
	$fred[2] = 'doo";

The array name itself (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, and Perl will treat them as different things, and wouldn't be confused.1   (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[2] in almost every place 2 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 sessions on scalar variables:

	print $fred[0];
	$fred[2] = "diddley";
	$fred[1] .= "whatsis";

Of course, the subscript may be any expression that gives a numeric value.  If it's not an integer already, it'll automatically be truncated to the next lower integer:

	$number = 2.71828;
	print $fred[$number - 1];	# Same as printing $fred[1]

If the subscript indicates an element that would be beyond the end of the array, the corresponding value will be undef.  This is just as with ordinary scalars; if your program has never stored a value into a scalar variable, then it's initial value is undef.

	$blank = $fred[ 142_857 ];	# unused array element gives undef
	$blanc = $mel;			# unused scalar $mel also gives undef

Next:  Special Array Indices

OR

Main Menu for this topic





























[1] The syntax is always unambiguous - tricky perhaps, but unambiguous.

Return to the page from whence you came






























[2] The most notable excepton is that the control variable of a foreach loop, which we'll see in a later lesson, must be a simple scalar.  And there are others, like the "indirect object slot" and "indirect filehandle slot" for print and printf.

Return to the page from whence you came