Copyright © tutorialspoint.com
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 variables are prefixed with the @ sign and are populated using either parentheses or the qw operator. For example:
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:
We can also populate an array by assigning each value individually:
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:
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:
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:
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:
There are only four elements in the array that contain information, but the array is 51 elements long, with a highest index of 50.
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.
#!/usr/bin/perl # 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. pop(@coins); print "Fourth Statement : @coins"; print "\n"; # Remove one element from the beginning of the array. shift(@coins); 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
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 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.
#!/usr/bin/perl @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
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.
#!/usr/bin/perl # 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; # This will print Roses print "\n"; # This is a new line print $names; # This will print Michael
Likewise, we can use the join() function to rejoin the array elements and form one long, scalar string.
#!/usr/bin/perl # 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 Rain,Drops,On,Roses,And,Whiskers,On,Kittens Larry-David-Roger-Ken-Michael-Tom
The sort() function sorts each element of an array according to ASCII Numeric standards.
#!/usr/bin/perl # Define an array @foods = qw(pizza steak chicken burgers); print "Before sorting: @foods\n"; # Sort this array @foods = sort(@foods); print "After sorting: @foods\n"; 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.
$[ 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.
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.
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());
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:
#!/usr/bin/perl $one = (5,4,3,2,1); print "Value of \$one is $one\n" This will produce follwoing result Value of $one is 1
Similarly, we can extract slices, although without the requirement for a leading @ character:
#!/usr/bin/perl @newlist = (5,4,3,2,1)[1..3]; print "value of new list is @newlist\n"; This will produce follwoing result value of new list is 4 3 2
Copyright © tutorialspoint.com