Table of Contents

More ways to access arrays

The element number can be a variable.

print "Enter a number :";
chomp ($x=<STDIN>);

@names=("Muriel","Gavin","Susanne","Sarah","Anna");

print "You requested element $x who is $names[$x]\n";

print "The index number of the last element is $#names \n";

This is useful. Notice the last line of the example. It returns the index number of the last element. Of course you could always just do this $last=scalar(@names)-1; but this is more efficient. It is an easy way to get the last element, as follows:

print "Enter the number of the element you wish to view :";
chomp ($x=<STDIN>);

@names=("Muriel","Gavin","Susanne","Sarah","Anna","Paul","Trish","Simon");

print "The first two elements are @names[0,1]\n";
print "The first three elements are @names[0..2]\n";
print "You requested element $x who is $names[$x-1]\n";		# starts at 0
print "The elements before and after are : @names[$x-2,$x]\n";
print "The first, second, third and fifth elements are @names[0..2,4]\n";

print "a) The last element is $names[$#names]\n";	# one way
print "b) The last element is @names[-1]\n";		# different way 

It looks complex, but it is not. Really. Notice you can have multiple values separated by a comma. As many as you like, in whatever order. The range operator .. gives you everything between and including the values. And finally look at how we print the last element - remember $#names gives us a number ? Simply enclose it inside square brackets and you have the last element.

Do also note that because element accesses such as [0,1] are more than one variable, we cannot use the scalar prefix, namely the $ symbol. We are accessing the array in list context, so we use the @ symbol. Doesn't matter that it is not the entire array. Remember, accessing more than one element of an array but not the entire array is called a slice. I won't go over the food analogies again.