Perl Script :Array elements

Array elements
To access the elements of an array, use the bracket operator:
print "$params[0] $params[2]\n";

The numbers in brackets are indices. This statement prints the element of @param with the index 0 and the element with index 2. The dollar sign indicates that the elements of the array are scalar values.

A scalar is a simple value that is treated as a unit with no parts, as opposed to array values, which are composed of elements. There are three types of scalar
values: numbers, strings, and references. In this case, the elements of the array are strings.

To store a scalar value, you have to use a scalar variable.
my $word = $params[0];
print "$word\n";

The dollar sign at the beginning of $word indicates that it is a scalar variable.
Since the name of the array is @params, it is tempting to write something like
# the following statement is wrong
my $word = @params[0];

The first line of this example is a comment. Comments begin with the hashcharacter (#) and end at the end of the line.As the comment indicates, the second line of the example is not correct, but as usual Perl tries to execute it anyway. As it happens, the result is correct, so it would be easy to miss the error. Again, there is a pragma that modifies Perl's
behavior so that it checks for things like this. If you add the following line to the program:
use warnings;
you get a warning like this:
Scalar value @params[0] better written as $params[0].

While you are learning Perl, it is a good idea to use strict and warnings to help you catch errors. Later, when you are working on bigger programs, it is a good idea to use strict and warnings to enforce good programming practice.
In other words, you should always use them.
You can get more than one element at a time from an array by putting a list of indices in brackets. The following program creates an array variable named @words and assigns to it a new array that contains elements 0 and 2 from
@params.
my @words = @params[0, 2];
print "@words\n";
The new array is called a slice.

No comments:

Post a Comment