1. Home
  2. Computing & Technology
  3. Perl

Beginning Perl Tutorial - Data Types: Lists

Accessing Array Elements

By Kirk Brown, About.com

Next: More on Quoted Strings

Since a list is just an ordered row of scalar 'boxes', and you access the entire list with the @arrayName, what happens if you just need one of the values in one of the boxes? Every element in the array is identified by a numeric address. Think of this as an address on a long row of mailboxes. They're numbered in order, but instead of starting at 1, they start at 0.

#!/usr/local/bin/perl
@myNumbers = (1, 2, 3, 4, 5);
print $myNumbers[1];
When you run the program above, you'll see it prints out 2. In this example, 2 is the value stored in the [1] (second) position of the @myNumbers array. Look close and you'll also notice that to access a specific element of your @list, you need to use a different method. Remember that a list is just a bunch of scalars, so if you want to access one of those scalars, you use the $scalar symbol, with the numeric address contained in brackets:
$myNumbers[1]
Next: More on Quoted Strings

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. Perl Tutorials
  5. Beginning Perl Tutorial - Data Types: Lists

©2008 About.com, a part of The New York Times Company.

All rights reserved.