Arrays and Lists


Arrays and lists are pretty much interchangeable concepts in perl. A list can be entered as a set of scalar values enclosed in parentheses, as shown:

 (1, "Branagh", 2.71828, $players)

Lists can contain any type of scalar value (or even other lists). Perl does not impose a limit on the size or number of elements in a list.

An array is just an ordered list in which you can refer to each element using its position. To assign the value of the preceding list to an array, you would write

 my @array = (1, "Branagh", 2.71828, $players);

Note that, where scalar variable names all start with $, array variable names start with @. You do not need to tell Perl how big you want the array to be-it will automatically make the array big enough to hold all the elements you add.

Once an array has been assigned a list, each element in the array can be accessed by referring to its index (starting from 0 for the first element):

 print "$array[1]\n";                            # prints "Branagh"

Here the @ has been replaced by a $. That’s because $array[1] is the string “Branagh”, which is a scalar. It’s only a piece of @array.

The index of the last element in an array is the number $#arrayname. You can also use the index 1 as a shortcut to get the last element (although you can’t count backward through the whole array with 2, 3, etc). To get the size of an array, you can use the expression scalar @arrayname. This causes Perl to use the scalar value of the array which is its size.

 my @flowers = ("Rosemary", "Rue", "Daisies", "Violets"); print "The " . scalar @flowers ."th flower "; print " (at index $#flowers) is $flowers[−1].\n";

This example will print the line “The 4th flower (at index 3) is Violets.”

You can create and initialize an array with the x operator.

 my @newarray = "0" x 10;

is shorthand for

 my @newarray = ("0", "0", "0", "0", "0", "0", "0", "0", "0", "0") ;

You can also create a list with the range operator,.. (dot dot). For example,

 my @newarray = ('A'..'Z');

The range operator simply creates a list containing all the values from one point to another. So, for example, (0..9) is a list with 10 elements, the integers from 0 to 9.

Reading and Printing Arrays

You can assign input from the keyboard to an array, just as you would a scalar variable.

 my @lines = <STDIN>;

This time, Perl will continue to read in lines as you enter them. Each line will be one entry in the array To finish entering data, type CTRL-D on a line by itself. Remember that the newline character will be included at the end of each line of text. To get rid of the newlines, use chomp:

 chomp (@lines);

or the shortcut

 chomp (my @lines = <STDIN>);

Printing an entire array works just like a scalar variable, too:

 print @lines;

If you didn’t use chomp to remove the trailing newlines, this will echo back the strings in the array just as you entered them, each on its own line. If you did remove the newlines, the strings will be concatenated together. You can use the command

 print "$_\n" foreach (@lines);

to print each one on a separate line. This is an example of a foreach loop, which will be explained later in this chapter.

Modifying Arrays

You can add one or more new elements to the end of an array with push.

 my @actors = ("Gielgud", "Olivier", "Branagh"); push (@actors, "Gibson", "Jacobi");

To remove the last element, use pop:

 print pop (@actors) . "\n";        # remove "Jacobi" # @actors now: ("Gielgud", "Olivier", "Branagh", "Gibson")

This will remove the last element from the array and print it at the same time.

The functions shift and unshift operate on the beginning of the array. shift removes the first element and shifts all the others back one index, while unshift adds a new first element and moves everything else up one index.

 shift (@actors);                   # remove the first element, "Gielgud" unshift (@actors, pop (@actors));  # move "Gibson" to the beginning # @actors now: ("Gibson", "Olivier", "Branagh")

The second line here removes the last element of the array with pop, and then it adds it at the beginning with unshift.

Array Slices

Perl allows you to assign part of an array, called a slice, to another array The following example creates a new array containing six elements from @players.

 my @subset = @players [0, 3, 6..9] ;

You can also use slices to assign new values to parts of an array For example, you could change the elements at indices 1 and 4 of @players with

 @players [1, 4] = ($playerK, $playerQ) ;

Another use for lists is to assign values to a group of variables all at once. For example, you could initialize the variables $x, $y, and $z with

 my ($x, $y, $z) = (.707, 1.414, 0) ;

Sorting Arrays

The sort function uses ASCII order (in which uppercase and lowercase letters are treated separately) to sort the elements of a list.

 my @newlist = sort (@oldlist) ;

The original list is not changed.

Somewhat unfortunately sort treats numbers as strings, which may not be what you want:

 my @numlist = sort (3, 25, 40, 100);

will put the numbers in ASCII order as 100, 25, 3, 40. To sort numerically, use the line

 my @sortednumlist = sort {$a <=> $b} @numlist;

This example uses a feature of sort that allows you to write your own comparison for the elements of your list. It uses a special built-in function, <=>, for the comparison. The web page http://perldoc.perl.org/functions/sort.html has more examples of custom sort routines.

The reverse function reverses the order of the elements in a list. It is often used after sort:

 chomp (my @wordlist = <STDIN>); my @revsort = reverse (sort (@wordlist)) ;




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net