Tuesday, May 07, 2013

Perl use an array variable

Perl, as many other languages has a array variable type. Accoording to Wikipedia an array is the following in computer science: In computer science, an array type is a data type that is meant to describe a collection of elements (values or variables), each selected by one or more indices (identifying keys) that can be computed at run time by the program. Such a collection is usually called an array variable, array value, or simply array. The use of an array is a very effective way of storing variabels in something that is most comparable to a list of things.

In the below example we stored some of the names of a phonetic alphabet in the variable phonetic:

my @phonetic = ( "Alpha", "Bravo", "Charlie", "Delta" );

Now if we want to do something with it we can call the variable @phonetic however this would give you the entire collection of all values in the array. For example using the print command:

my @phonetic = ( "Alpha", "Bravo", "Charlie", "Delta" );

print @phonetic;

this would give you a result you most likely do not want, namely:
AlphaBravoCharlieDelta

As you can see this is printed without any space between it or a newline. Simply using all the values from the array in the print command at once. In many cases you would like to take all the values of the array one by one. In some cases, for example adding up all the numerical values in the array, you might want to use it in this way however in most cases you would like to loop value per value.

In the example below we loop the array and do a print for every value in the array.

my @phonetic = ( "Alpha", "Bravo", "Charlie", "Delta" );

foreach (@phonetic) {
 print $_ . "\n";
}

When running this example you will see that we do not get the result all in one line as was with direct print on the array. Now we will have a result as shown below;

Alpha
Bravo
Charlie
Delta

In some cases you would like to do an action on a certain value. Every value in an array has an index number (starting at 0). So lets say we want to print the value Charlie we have to call the array value with the index number 2. The below example will print the value "Charlie"

my @phonetic = ( "Alpha", "Bravo", "Charlie", "Delta" );

print @phonetic[2];

No comments: