PERL Array Variable

An array is just a set of scalars. It’s made up of a list of individual scalars that are stored within a single variable. You can refer to each scalar within that list using a numerical index.

Array Creation:

Array variables are prefixed with the @ sign and are populated using either parentheses or the qw operator. For example:
@array = (1, 2, 'Hello');
@array = qw/This is an array/;

The second line uses the qw// operator, which returns a list of strings, separating the delimited string by white space. In this example, this leads to a four-element array; the first element is ‘this’ and last (fourth) is ‘array’. This means that you can use newlines within the specification:
@days = qw/Monday
We can also populate an array by assigning each value individually:
$array[0] = 'Monday';
$array[6] = 'Sunday';

Extracting Individual Indices

When extracting individual elements from an array, you must prefix the variable with a dollar sign and then append the element index within square brackets after the name. For example:

@shortdays = qw/Mon Tue Wed Thu Fri Sat Sun/;
print $shortdays[1];

This will print

Array indices start at zero, so in the preceding example actually printed “Tue”. You can also give a negative which case you select the element from the end, rather than the beginning, of the array. This means that

print $shortdays[0]; # Outputs Mon
print $shortdays[6]; # Outputs Sun
print $shortdays[-1]; # Also outputs Sun
print $shortdays[-7]; # Outputs Mon

Sequential Number Arrays

PERL offers a shortcut for sequential numbers and letters. Rather than typing out each element when counting to 100 for example, we can do something like this:

@10 = (1 .. 10);
@100 = (1 .. 100;
@1000 = (100 .. 1000);
@abc = (a .. z);

print "@10"; # Prints number starting from 1 to 10
print "@100"; # Prints number starting from 1 to 100
print "@1000"; # Prints number starting from 1 to 1000
print "@abc"; # Prints number starting from a to z

Array Size

The size of an array can be determined using scalar context on the array – the returned value will be the number of elements in the array:
@array = (1,2,3);
print "Size: ",scalar @array,"n";
The value returned will always be the physical size of the array, not the number of valid elements. You can demonstrate this, and the difference between scalar @array and $#array, using this fragment:

@array = (1,2,3);
$array[50] = 4;

print "Size: ",scalar @array,"n";
print "Max Index: ", $#array,"n";

This will return
Size: 51
Max Index: 50
There are only four elements in the array that contain information, but the array is 51 elements long, with a highest index of 50.
Here scalar function is used to enforce scalar context so that @array can return
size of the array otherwise @array will return a lisrt of all the elements contacined in it.

Adding and Removing Elements in Array

Use the following functions to add/remove and elements:
  • push(): adds an element to the end of an array.
  • unshift(): adds an element to the beginning of an array.
  • pop(): removes the last element of an array.
  • shift() : removes the first element of an array.
When adding elements using push() or shift() you must specify two arguments, first the array name and second the name of the element to add. Removing an element with pop() or shift() only requires that you send the array as an argument.

# Define an array
@coins = ("Quarter","Dime","Nickel");
print "First Statement : @coins";
print "n";

# Add one element at the end of the array
push(@coins, "Penny");
print "Second Statement : @coins";
print "n";
# Add one element at the beginning of the array
unshift(@coins, "Dollar");
print "Third Statement : @coins";
print "n";

# Remove one element from the last of the array.
print "Fourth Statement : @coins";
print "n";
# Remove one element from the beginning of the array.
print "Fifth Statement : @coins";
print "@coins";

Now this will produce following result
First Statement : Quarter Dime Nickel
Second Statement : Quarter Dime Nickel Penny
Third Statement : Dollar Quarter Dime Nickel Penny
Fourth Statement : Dollar Quarter Dime Nickel
Fifth Statement : Quarter Dime Nickel

Slicing Array Elements

You can also extract a “slice” from an array – that is, you can select more than one item from an array in order to produce another array.
@weekdays = @shortdays[0,1,2,3,4];
The specification for a slice must a list of valid indices, either positive or negative, each separated by a comma. For speed, you can also use the .. range operator:
@weekdays = @shortdays[0..4];
Ranges also work in lists:
@weekdays = @shortdays[0..2,6,7];

Replacing Array Elements

Replacing elements is possible with the splice() function. Splice() requires a handful of arguments and the formula reads:
splice(@array,first-element,sequential_length, new elements)
Essentially, you send PERL an array to splice, then direct it to the starting element, count through how many elements to replace, and then fill in the missing elements with new information.

@nums = (1..20);
splice(@nums, 5,5,21..25);
print "@nums";
Here actual replacement begins after the 5th element, starting with the number 6. Five elements are then replaced from 6-10 with the numbers 21-25

Transform Strings to Arrays

With the split function, it is possible to transform a string into an array. To do this simply define an array and set it equal to a split function. The split
function requires two arguments, first the character of which to split and also the string variable.

# Define Strings
$astring = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$namelist = "Larry,David,Roger,Ken,Michael,Tom";

# Strings are now arrays. Here '-' and ',' works as delimeter
@array = split('-',$astring);
@names = split(',',$namelist);

print $array[3]; # This will print Roses
print "n"; # This is a new line
print $names[4]; # This will print Michael
Likewise, we can use the join() function to rejoin the array elements and form one long, scalar string.

# Define Strings
$astring = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens";
$namelist = "Larry,David,Roger,Ken,Michael,Tom";

# Strings are now arrays. Here '-' and ',' works as delimeter
@array = split('-',$astring);
@names = split(',',$namelist);

$string1 = join(",", @array);
$string2 = join("-", @names);

print $string1;
print "n" ;
print $string2;

This will produce following result

Sorting Arrays

The sort() function sorts each element of an array according to ASCII Numeric standards.

# Define an array
@foods = qw(pizza steak chicken burgers);
print "Before sorting: @foodsn";

# Sort this array
@foods = sort(@foods);
print "After sorting: @foodsn";

This will produce following result
Before sorting: pizza steak chicken burgers
After sorting: burgers chicken pizza steak
Please note that sorting is performed based on ASCII Numeric value of the words. So the best option is to first transform every element of the array into lowercase letters and then perform the sort function.

The $[ Special Variable

$[ is a special variable. This particular variable is a scalar containing the first index of all arrays. because Perl arrays have zero-based indexing, $[ will almost always be 0. But if you set $[ to 1 then all your arrays will use on-based indexing. It is recommended not to use any other indexing other than zero.

The Lists

Lists are really a special type of array – .essentially, a list is a temporary construct that holds a series of values. The list can be “hand” generated using parentheses and the comma operator,
@array = (1,2,3);
or it can be the value returned by a function or variable when evaluated in list context:
print join(',' @array);
Here, the @array is being evaluated in list context because the join function is expecting a list.

Merging Lists (or Arrays)

Because a list is just a comma-separated sequence of values, you can combine lists together:
@numbers = (1,3,(4,5,6));
The embedded list just becomes part of the main list.this also means that we can combine arrays together:
@numbers = (@odd,@even);
Functions that return lists can also be embedded to produce a single, final list:
@numbers = (primes(),squares());

Selecting Elements from Lists

The list notation is identical to that for arrays – .you can extract an element from an array by appending square brackets to the list and giving one or more indices:

$one = (5,4,3,2,1)[4];

print "Value of $one is $onen"

This will produce follwoing result
Value of $one is 1
Similarly, we can extract slices, although without the requirement for a leading @ character:

@newlist = (5,4,3,2,1)[1..3];

print "value of new list is @newlistn";

This will produce follwoing result
value of new list is 4 3 2

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s