A.6 Arrays


Arrays are ordered collections of zero or more scalar values, indexed by position. An array variable begins with the @ sign followed by a legal variable name . For instance, here are two possible array variable names :

 @array1 @dna_fragments 

You can assign scalar values to an array by placing the scalar values in a list separated by commas and surrounded by a pair of parentheses. For instance, you can assign an array the empty list:

 @array = (  ); 

or one or more scalar values:

 @dna_fragments = ('ACGT', $fragment2, 'GGCGGA'); 

Notice that it's okay to specify a scalar variable such as $fragment2 in a list. Its current value, not the variable name, is placed into the array.

The individual scalar values of an array (the elements) are indexed by their position in the array. The index numbers begin at 0. You can specify the individual elements of an array by preceding the array name by a $ and following it with the index number of the element within square brackets, like so:

 $dna_fragments[2] 

This equals the value of ' GGCGGA ', given the values previously set for this array. Notice that the array has three scalar values indexed by numbers 0, 1, and 2. The third and last element is indexed 2, one less than the total number of elements 3, because the first element is indexed number 0.

You can make a copy of an array using an assignment operator = , as in this example that makes a copy @output of an existing array @input :

 @output = @input; 

If you evaluate an array in scalar context, the value is the number of elements in the array. So if array @input has five elements, the following example assigns the value 5 to $count :

 $count = @input; 

Figure A-1 shows an array @myarray with three elements, which demonstrates the ordered nature of an array by which each element appears and can be found by its position in the array.

Figure A-1. Schematic of an array
figs/mpb_aa01.gif

You can make a reference to an array by preceding it with a backslash; you dereference it by preceding the reference with an at sign @ for the entire array or with an extra dollar sign $ for an individual element of the array:

 @a = ( 'one', 'two', 'three'); $aref =  a; print $aref, "\n"; print $$aref[0], "\n"; print "@$aref", "\n"; 

gives the output:

 ARRAY(0x811d1e0) one one two three 

You can also define an array as an anonymous array. An anonymous array isn't saved in a named array variable; it's a reference to array data and can only be saved in a reference. It's initialized within square brackets:

 $anonarray = [ 'one', 'two', 'three']; print "@$anonarray", "\n"; 

gives the output:

 one two three 


Mastering Perl for Bioinformatics
Mastering Perl for Bioinformatics
ISBN: 0596003072
EAN: 2147483647
Year: 2003
Pages: 156

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