Perl Tutorial - Practical Extraction and Reporting Language (Perl)
Please leave a remark at the bottom of each page with your useful suggestion.
Table of Contents
- Perl Introduction
- Perl Program Startup
- Perl Regular Expressions
- Perl Array Program
- Perl Basic Program
- Perl Subroutine / Function Program
- Perl XML Program
- Perl String Program
- Perl Statement Program
- Perl Network Program
- Perl Hash Program
- Perl File Handling Program
- Perl Data Type Program
- Perl Database Program
- Perl Class Program
- Perl CGI Program
- Perl GUI Program
- Perl Report Program
Perl Array Program
Access array element by index
#!/usr/bin/perl -w
use strict;
print(('salt', 'vinegar', 'mustard', 'pepper')[2]);
print "\n";
Accessing Elements: Populating an array and printing its values
@names=('John', 'Joe', 'Jake');
print @names, "\n";
print "Hi $names[0], $names[1], and $names[2]!\n";
$number=@names;
print "$number elements in the \@names array.\n";
print "The last element is $names[$number - 1].\n";
print "The last element is $names[$#names].\n";
@fruit = qw(a b c d);
print "The first element of the \@fruit array is $fruit[0];the second element is $fruit[1].\n";
print "@fruit[-1, -3]\n";
Accessing List Values
#!/usr/bin/perl
use warnings;
use strict;
print (('A', 'v', 'm', 'p')[2]);
print "\n";
Add elements to @array by referring to nonexistent element 3.
# There are now 4 elements in the array. Elements 1 and 2 have undefined values.
$array[ 3 ] = "birthday";
print "@array\n\n";
Adding a hash to the array
my $petref = [ { "name" => "Jack",
"type" => "dog"
},
{ "name" => "Tom",
"type" => "cat"
}
];
push @{$petref},{ "owner"=>"Mary", "name"=>"Tweety"};
while(($key,$value)=each %{$petref->[2]}){
print "$key -- $value\n";
}
Adding array items from one array to another array
#!/usr/bin/perl -w
use strict;
my @array1 = (1, 2, 3);
my @array2;
@array2 = (@array1, 4, 5, 6);
print "@array2\n";
Adding more elements to an array
@array = (1, 2, 3);
$array[5] = "Here is a new element!";
print "$array[5]\n";
Adding to an Array
#!/usr/bin/perl
use warnings;
use strict;
my @array1 = (1, 2, 3);
my @array2;
@array2 = (@array1, 4, 5, 6);
print "@array2\n";
@array2 = (3, 5, 7, 9);
@array2 = (1, @array2, 11);
print "@array2\n";
Adding two arrays together
@a1 = ("one", "two", "three");
@a2 = @a1;
@a3 = @a1 + @a2;
print "@a3";
An array is a named list.
# When you use an array variable, you use the @ character
#!/usr/bin/perl -w
# Array example.
@array = (1,2,3,'red');
print "@array\n";
# You can mix and match numbers and text in Perl arrays.
An array is an ordered list of scalars: strings and/or numbers.
#The elements of the array are indexed by integers starting at 0.
#The name of the array is preceeded by an "@" sign.
@names = ( "J", "M", "L" );
print "@names"; # Prints the array with elements separated by a space
print "$names[0] and $names[2]";
print "$names[-1]\n";
$names[3]="N"; # Assign a new value as the 4th element
An array on the left of a list assignment receives all remaining initializers in the list on the right side of a list assignment
@array = qw( zero one two three four five six seven eight nine );
print "@array\n\n";
( $first, @array2, $second ) = ( 1 .. 8 );
print "\$first = $first\n";
print "\@array2 = @array2\n";
print "\$second = $second\n";
An empty list is represented as parentheses with nothing in between
#Each element of an array is a scalar value.
#Each element of an array can be accessed using the Perl syntax for scalars, $, with an index into the array.
#Perl starts counting array indices with 0.
() # Empty list.
@array = (1,2,3,'red');
print "@array\n";
print "$array[1]\n";
# Assignment.
$array[2] = 'maroon';
print "@array\n";
Append to array
#!/usr/bin/perl
use strict;
use warnings;
my @array = ('a', 'b', 'c', 'd', 'e', 'f');
print "@array \n"; # produces 'a b c d e f'
$array[6] = "g";
print "@array \n"; # produces 'a b c d e f g'
Append two arrays to form another array
#!c:/perl/bin
@warships=('H', 'B', 'W');
@passengerships=('T', 'O', 'B');
@ships = (@warships, @passengerships);
print "@ships[0] \n";
print "@ships[1] \n";
print "@ships[2] \n";
print "@ships[3] \n";
print "@ships[4] \n";
print "@ships[5] \n";
A program containing overlapping array slices.
#!/usr/local/bin/perl
@array = ("one", "two", "three", "four", "five");
@array[1,2,3] = @array[2,3,4];
print ("@array\n");
A program that assigns a list as part of another list.
#!/usr/local/bin/perl
@innerlist = " abc ";
@outerlist = ("I", @innerlist, "fail!\n");
print @outerlist;
A program that assigns to an array slice.
#!/usr/local/bin/perl
@array = ("old1", "old2", "old3", "old4");
@array[1,2] = ("new2", "new3");
print ("@array\n");
A program that copies an array and compares the elements of the two arrays.
#!/usr/local/bin/perl
@array1 = (14, "abc", 1.23, -7, "def");
@array2 = @array1;
$count = 1;
while ($count <= 5) {
print("element $count: $array1[$count-1] ");
print("$array2[$count-1]\n");
$count++;
}
A program that demonstrates the use of an array slice.
#!/usr/local/bin/perl
@array = (1, 2, 3, 4);
@subarray = @array[1,2];
print ("The first element of subarray is $subarray[0]\n");
print ("The second element of subarray is $subarray[1]\n");
A program that prints every element of an array.
#!/usr/local/bin/perl
@array = (14, "abc", 1.23, -7, "ddd");
$count = 1;
while ($count <= @array) {
print("element $count: $array[$count-1]\n");
$count++;
}
A program that prints the elements of a list.
#!/usr/local/bin/perl
@array = (1, "chicken", 1.23, "\"Having fun?\"", 9.33e+23);
$count = 1;
while ($count <= 5) {
print ("element $count is $array[$count-1]\n");
$count++;
}
A program that reads data into an array and writes the array.
#!/usr/local/bin/perl
@array = <STDIN>;
print (@array);
A program that sorts an array.
#!/usr/local/bin/perl
# read the array from standard input one item at a time
print ("Enter the array to sort, one item at a time.\n");
print ("Enter an empty line to quit.\n");
$count = 1;
$inputline = <STDIN>;
chop ($inputline);
while ($inputline ne "") {
@array[$count-1] = $inputline;
$count++;
$inputline = <STDIN>;
chop ($inputline);
}
# now sort the array
$count = 1;
while ($count < @array) {
$x = 1;
while ($x < @array) {
if ($array[$x - 1] gt $array[$x]) {
@array[$x-1,$x] = @array[$x,$x-1];
}
$x++;
}
$count++;
}
print ("@array\n");
A program that uses an array variable as an array-slice subscript.
#!/usr/local/bin/perl
@array = ("one", "two", "three", "four", "five");
@range = (1, 2, 3);
@subarray = @array[@range];
print ("The array slice is: @subarray\n");
Array Elements
#!/usr/bin/perl
use warnings;
use strict;
my @band = qw(A B C D);
my $ref = \@band;
for (0..3) {
print "Array : ", $band[$_] , "\n";
print "Reference: ", ${$ref}[$_], "\n";
}
Array Elements Assigned to a Slice
@digits = (11..21);
@slice[10..20] = (@digits);
print "@slice\n";
print "last index is $#slice.\n";
@09 = (0..9);
@slice[@09] = (@digits);
print "@slice\n";
print "last index is $#slice.\n";
@slice[1,3,5,7,9] = (2,4,6,8,10);
@evenNumbers = @slice[1,3,5,7,9];
print "array: @evenNumbers\n";
print "The last index is $#evenNumbers.\n";
@slice[@digits,77,55,33] = (1,2,3,4,4,5,6,6,7,5,6,7,6,7,8);
print "array are: @slice\n";
print "Indexes 55, 33, 77, and 12 in that order are: @slice[55,33,77,12]\n";
print "The last index of the array is $#slice.\n";
@names = (David, Mary, Thomas, Dewey, Steve, Martin);
printNames(@names);
for ($i=0; $i<=$#names; $i= $i+2){
@names[$i+1, $i] = @names[$i, $i+1];
}
printNames(@names);
sub printNames (@){
my (@names) = @_;
for ($i=0; $i<= $#names;){
print "$names[$i++], $names[$i++]\n";
}
}
Array index in action
#!c:/perl/bin
@ships=('B', 'T', 'H');
print "@ships[0] \n";
print "@ships[1] \n";
print "@ships[2] \n";
Array literal
#!C:/perl/bin
@passengerships = ('T', 'O', 'B');
print "@passengerships \n";
Array of array
$array[0] = ["A", "AA"];
$array[1] = ["B", "BB", "CCC"];
$array[2] = ["D", "DD"];
print $array[1][1];
Array of Hashes
my $petref = [ { "name" => "Jack",
"type" => "dog"
},
{ "name" => "Tom",
"type" => "cat"
}
];
print "$petref->[0]->{name}.\n";
for($i=0; $i<2; $i++){
while(($key,$value)=each %{$petref->[$i]} ){
print "$key -- $value\n";
}
print "\n";
}
Arrays: a collection of similar data elements
@name=("A", "B", "C", "D");
@list=(2..10);
@grades=(100, 90, 65, 96);
@items=($a, $b, $c);
@empty=();
$size=@items;
@mammals = qw/dogs cats cows/;
@fruit = qw(apples pears peaches);
Arrays in Perl
#!perl
@array = ( "A", "B", "C", "D" );
print "The array contains: @array\n";
print "Printing array outside of quotes: ", @array, "\n\n";
print "Third element: $array[ 2 ]\n";
$number = 3;
print "Fourth element: $array[ $number ]\n\n";
@array2 = ( A..Z );
print "The range operator is used to create a list of\n";
print "all letters from capital A to Z:\n";
print "@array2 \n\n";
$array3[ 3 ] = "4th";
print "Array with just one element initialized: @array3 \n\n";
print 'Printing literal using single quotes: @array and \n', "\n";
print "Printing literal using backslashes: \@array and \\n\n";
Array Slices
# Array slices
@names=('A', 'B', 'C', 'D' );
@pal=@names[1,2,3];
print "@pal\n\n";
($friend[0], $friend[1], $friend[2])=@names;
print "@friend\n";
Array slices 2
@colors=('red','green','yellow','orange');
($c[0], $c[1],$c[3], $c[5])=@colors; # The slice
print @colors,"\n";
print "@colors,\n";
print $c[0],"\n";
print $c[1],"\n";
print $c[2],"\n";
print $c[3],"\n";
print $c[4],"\n";
print $c[5],"\n";
print "The size of the \@c array is ", $#c + 1,".\n";
ASCII and Numeric Sort Using Subroutine
@list=("A","B", "C","D" );
print "Original list: @list\n";
# ASCII sort using a subroutine
sub asc_sort{
$a cmp $b; # Sort ascending order
}
@sorted_list=sort asc_sort(@list);
print "Ascii sort: @sorted_list\n";
# Numeric sort using subroutine
sub numeric_sort {
$a <=> $b ;
} # $a and $b are compared numerically
@number_sort=sort numeric_sort 10, 0, 5, 9.5, 10, 1000;
print "Numeric sort: @number_sort.\n";
Assign array value to a list of scalar variables
#!/usr/bin/perl -w
my $scalar0;
my $scalar1;
my $scalar2;
my @array = (10, 20, 30);
($scalar0, $scalar1, $scalar2) = @array;
print "Scalar zero is $scalar0\n";
print "Scalar one is $scalar1\n";
print "Scalar two is $scalar2\n";
Assign array variable to scalar variable
@array = (1, 2, 3);
$variable = @array;
print "\@array has $variable elements.";
Assigning An Array To A Scalar
#!/usr/bin/perl
use warnings;
use strict;
my @array1;
my $scalar1;
@array1 = qw(Monday Tuesday Wednesday Thursday Friday Saturday Sunday);
$scalar1 = @array1;
print "Array 1 is @array1\nScalar 1 is $scalar1\n";
my @array2;
my $scalar2;
@array2 = qw(Winter Spring Summer Autumn);
$scalar2 = @array2;
print "Array 2 is @array2\nScalar 2 is $scalar2\n";
Assigning an array value to a scalar variabe
@a = (2, 4, 6);
$a = @a;
print $a;
Assigning one array variable to another variable
@a1 = ("one", "two", "three");
@a2 = @a1;
print $a2[1];
Assign returning array value from a function to an array
for $loopindex (0..4) {
$array[$loopindex] = [&zerolist];
}
sub zerolist
{
return (0, 0, 0, 0);
}
print $array[1][1];
A three-dimensional array
@array =
(
[
["apple", "orange"],
["ham", "chicken"],
],
[
["tomatoes", "sprouts", "potatoes"],
["asparagus", "corn", "peas"],
],
);
print $array[1][1][1];
Binary search of an array
for ( $i = 0; $i < 15; ++$i ) {
$array[ $i ] = 2 * $i;
}
print "Enter an integer search key: ";
chomp ( $searchKey = <STDIN> );
print "\n";
for ( $i = 0; $i < @array; ++$i ) {
print $i < 10 ? " $i " : " $i ";
}
print "\n", "-" x ( 4 * @array ), "\n";
$found = 0; # search while !$found
$lowIndex = 0; # start index for search
$highIndex = $#array; # end index for search
while ( $lowIndex <= $highIndex && !$found ) {
$middleIndex = ( $lowIndex + $highIndex ) / 2;
for ( $i = 0; $i < @array; ++$i ) {
if ( $i < $lowIndex || $i > $highIndex ) {
print " ";
}
elsif ( $i == $middleIndex ) {
print $array[ $i ] < 10 ? " $array[ $i ]*" : " $array[ $i ]*";
}
else {
print $array[ $i ] < 10 ? " $array[ $i ] " : " $array[ $i ] ";
}
}
print "\n";
if ( $searchKey == $array[ $middleIndex ] ) { # match
$index = $middleIndex;
$found = 1;
}
elsif ( $searchKey < $array[ $middleIndex ] ) {
$highIndex = $middleIndex - 1; # search low end of array
}
else {
$lowIndex = $middleIndex + 1; # search high end of array
}
}
# display results
if ( $found ) { # $found == 1
print "\nFound $searchKey at subscript $index \n";
}
else { # $found == 0
print "\n$searchKey not found \n";
}
Build 4-element array, each with references to another array
@words = (one, two, three, four, five, six, seven, eight, nine, ten, );
@codeNumbers = (1,2,3,4,5,6,7,8,9,10);
@codeLetters = (A,B,C,D,E,F,G,H,I,J);
@codes[0] = \@words;
@codes[1] = \@codeNumbers;
@codes[2] = \@codeLetters;
@codes[3] = \@myValue;
for ($index = $codes[3]->[1]->[0] ; $index <= $#{$codes[3]->[1]}; $index++){
$codeIndex = $codes[1][$index];
$codeWord = $codes[0][$codeIndex];
$codeLetter = $codes[2]->[$codes[1][$index]];
print "$codeWord\t : $codeLetter\n";
}
Build a string array across two lines
@array = (
"one", "two", "three",
"four", "five", "six",
);
print @array;
Change array length by adding new element to an array
@array = (1, 2, 3);
$array[5] = "Here is a new element!";
print "$array[5]\n";
Change array length by assigning new length to an array
@array = (1, 2, 3);
$#array = 10;
$array[5] = "Here is a new element!";
print "$array[5]\n";
Change value in an array
@array = (1, 2, 3);
foreach $element (@array) {
$element++;
}
print join(", ", @array);
Character and Number Sorts
@names = (Tom, Tom, James, Pete, Cindy, Carol);
@names = sort @names;
print "@names\n";
@numbers = (12,45,36,14,258,1,2,4,);
@numbers = sort @numbers;
print "@numbers\n";
@numbers = sort sortNumbers @numbers;
print "@numbers\n";
sub sortNumbers(){
$a <=> $b;
}
chop and chomp Functions with Lists
The chop function chops off the last character of a string and returns the chopped character
The chomp function removes the last character of each element in a list if it ends with a newline and returns the number of newlines it removed.
# Chopping and chomping a list
@line=("red", "green", "orange");
chop(@line); # Chops the last character off each string in the list
print "@line";
@line=( "red", "green", "orange");
chomp(@line); # Chomps the newline off each string in the list
print "@line";
Construct an integer array and output its first element
@array = (1, 2, 3);
print $array[0];
Construct a string array and output its first element
@array = ("one", "two", "three");
print @array;
Constructing and Dereferencing
#!/usr/bin/perl
use warnings;
use strict;
my @array = (1, 2, 3, 4, 5);
my $array_r = \@array;
print "This is our dereferenced array: @{$array_r}\n";
for (@{$array_r}) {
print "An element: $_\n";
}
print "The highest element is number $#{$array_r}\n";
print "This is what our reference looks like: $array_r\n";
Convert array to scalar
#!C:/perl/bin
@passengerships = ('T', 'O', 'B');
print "@passengerships \n";
print scalar(@passengerships);
Create @array with one element by referring to nonexistent element 0
$array[ 0 ] = "happy";
print "@array\n";
Create array with range operator
#!/usr/bin/perl
use warnings;
use strict;
my $max = 20;
my @array = (1..$max-1);
while (my $element = shift @array) {
push (@array, $max - $element);
sleep 1;
print '*' x $element, "\n";
}
Create lists of number variables
#!/usr/bin/perl
print "Content-Type: text/html \n\n";
# This script demonstrates how to create a numeric array.
@AcmeInventory = (178,286,387);
print @AcmeInventory;
print "<p>We just created a list of numbers using an array variable!";
Create lists of text variables
#!/usr/bin/perl
print "Content-Type: text/html \n\n";
# This script demonstrates how to create a text array.
@AcmeCars = ("Ford","Dodge","Chevy");
print "@AcmeCars";
print "<p>We have just created a text
array!</p>";
Creating and initializing an array with list assignment
@array = ( "Hello", 283, "there", 16.439 );
# display every element of the array
$i = 0;
while ( $i < 4 ) {
print "$i $array[ $i ]\n";
++$i;
}
Define an array variable called @myList.
#array variable is preceded by @; this tells Perl that we want an array, not a scalar.
@myList = ();
Define two dimensional array
@array = (
["A", "F"],
["B", "E", "G"],
["C", "D"],
);
print @array[1][1];
Delete all remaining elements
@array = ( 0 .. 20 );
@array2 = ( A .. F );
print "\@array: @array\n";
print "\@array2: @array2\n\n";
splice( @array );
unless ( @array ) {
print "\@array has no elements remaining\n";
}
dereferenced array
#!/usr/bin/perl -w
use strict;
my @array = (2, 4, 6, 8, 10);
my $array_r = \@array;
print "This is our dereferenced array: @{$array_r}\n";
Determine the mean
@opinions = ( 8, 9, 4, 7, 8, 5, 6, 4, 9, 9,
6, 7, 3, 4, 8, 7, 9, 8, 9, 2 );
$total = 0;
foreach ( @opinions ) {
$total += $_;
}
print $total;
@opinions = ( 8, 9, 4, 7, 8, 5, 6, 4, 9, 9,
6, 7, 3, 4, 8, 7, 9, 8, 9, 2 );
# determine the mean
$total = 0;
foreach ( @opinions ) {
$total += $_;
}
$mean = $total / @opinions;
print "Survey mean result: $mean\n";
Directly indexing an array's contents:
#!/usr/local/bin/perl -w
my @months = qw (JUNK Jan Feb March April May June July Aug Sept Oct Nov Dec);
for ($x=0; $x <= $#months; $x++)
{
print "Index[$x] = $months[$x]\n";
}
Discard words until we see the "A" marker
#!/usr/bin/perl
use warnings;
use strict;
my @lines = ("C", "B", "A", "E", "D");
while (my $line = shift @lines) {
last if $line eq 'A';
}
print "@lines";
Displaying slices of @array
@array = qw( zero one two three four five six seven eight nine );
print "@array\n\n";
print "@array[ 1, 3, 5, 7, 9 ]\n";
print "@array[ 2 .. 6 ]\n\n";
double each element of an array
#!/usr/bin/perl
use warnings;
use strict;
my @array=(10, 20, 30, 40);
print "Before: @array\n";
for (@array) { $_ *= 2 }
print "After: @array\n";
Duplicate array elements
#!c:/perl/bin
@zeros = (0) x 250;
for($loopcount=0; $loopcount < 250; $loopcount++)
{
print "$loopcount = @zeros[$loopcount] \n";
}
print "There are $#zeros in the \$zeros array \n";
Empty list
#!/usr/bin/perl -w
use strict;
if ( (()) ) {
print "Yes, it is.\n";
}
exists function returns true if an array index (or hash key) has been defined, and false if it has not.
#Format: exists $ARRAY[index];
#!/usr/bin/perl
@names = qw(Tom Raul Steve Jon);
print "Hello $names[1]\n", if exists $names[1];
print "Out of range!\n", if not exists $names[5];
Filling an array with 100 zeroes by using the 'x' operator
@array = (0) x 100;
print @array;
Filling an array with a sequence of numbers by using the '..' operator
@array = (1 .. 10);
print @array;
Get array element by index
#!/usr/bin/perl
use strict;
use warnings;
my @array = ("First", "Second");
foreach (0..$#array) {
print "Element number $_ contains $array[$_] \n";
}
Get array last element
#!/usr/bin/perl -w
use strict;
my @array = (2, 4, 6, 8);
print "the last element is: ", $array[$#array], "\n";
Get array last index
#!/usr/bin/perl -w
use strict;
my @array = (2, 4, 6, 8);
print "the last index is: ", $#array, "\n";
Get array length
#!c:/perl/bin
@warships=('H', 'B', 'W');
@passengerships=('T', 'O', 'B');
@ships = (@warships, @passengerships);
print "There are $#ships in the \$ships array \n";
Get the array length by assigning the array variable to a scalar variable
#!/usr/bin/perl -w
use strict;
my @array1;
my $scalar1;
@array1 = qw(Monday Tuesday Wednesday Thursday Friday Saturday Sunday);
$scalar1 = @array1;
print "Array 1 is @array1\nScalar 1 is $scalar1\n";
Get the return value of reverse function
@a1 = (1, 2, 3, 4, 5, 6);
@a2 = reverse @a1;
Get two variables from array
($atime, $mtime) = (stat 'timer.pl')[8, 9];
How to use two dimensional arrays
#!/usr/bin/perl
use warnings;
use strict;
my @array;
foreach my $outer ( 0 .. 3 ) {
foreach my $inner ( 0 .. 3 ) {
$array[ $outer ][ $inner ] = $outer * $inner;
}
}
foreach ( 0 .. $#array ) {
$array[ $_ ]->[ 4 ] = $_ * 4;
}
print( "@array\n" );
Increase the number of elements to 11
@array = qw( zero one two three four five six seven eight nine );
$#array = 10;
print "@array.\n";
Index an array
#!/usr/bin/perl
use warnings;
use strict;
my @questions = qw(Java Python Perl C);
my @punchlines = ("A","B","C",'D');
for (0..$#questions) {
print "How many $questions[$_] ";
sleep 2;
print $punchlines[$_], "\n\n";
sleep 1;
}
$# is the array size
#!C:/perl/bin
@passengerships = ('T', 'O', 'B');
print "@passengerships \n";
print scalar(@passengerships);
print "\n\n";
print $#passengerships;
print "\n\n";
$arraysize = @passengerships;
print $arraysize;
Join array
@array = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
print join(", ", @array);
Joining each element of a list with a newline
@names=('A','C','C','D','E');
@names=join("\n", sort(@names));
print @names,"\n";
Linear search of an array.
# populate @array with the even integers from 0 to 198
for ( $i = 0; $i < 100; ++$i ) {
$array[ $i ] = 2 * $i;
}
# prompt the user for a search key
print "Enter an integer search key: ";
chomp ( $searchKey = <STDIN> );
$found = 0; # $found is initially false
for ( $i = 0; $i < @array && !$found; ++$i ) {
if ( $array[ $i ] == $searchKey ) {
$index = $i;
$found = 1;
}
}
if ( $found ) { # $found == 1
print "Found $searchKey at subscript $index \n";
}
else { # $found == 0
print "$searchKey not found \n";
}
Lists Assigned to Arrays
#!/usr/local/bin/perl
@mixedData = (\@mixedData,,8,,3.14,,"Last");
printArray(@mixedData);
@mixedData = (\@mixedData,'',8,'',3.1,'',"Last");
printArray(@mixedData);
@pieces = @mixedData[4..8];
printArray(@pieces);
@all = @mixedData;
printArray(@all);
sub printArray {
my @localArray = @_;
$i = 0;
foreach $value (@localArray){
print "Cell number $i = $value \n";
$i++;
}
print "The last cell of the array is $#localArray";
print "\n\n";
}
Lists of Lists
#!/bin/perl
my $arrays = [ '1', '2', '3', [ 'red', 'blue', 'green' ]];
for($i=0;$i<3;$i++){
print $arrays->[$i],"\n";
}
for($i=0;$i<3;$i++){
print $arrays->[3]->[$i],"\n";
}
print "@{$arrays}\n";
print "--@{$arrays->[3]}--", "\n";
Loop through a list
foreach $Index (1..10) {
$i = $Index - 1;
$Array[$i] = $Index ** 3;
}
Loop through the array and replace every undefined value with an actual value.
for ( $i = 0; $i < 4; ++$i ) {
# if the element is not defined, assign it a value
if ( ! defined( $array[ $i ] ) ) {
$array[ $i ] = "happy";
}
}
print "@array\n";
print @array, "\n";
Map to an array
@a = (1 .. 10);
map {$_ *= 2} (@a);
print join(", ", @a);
2, 4, 6, 8, 10, 12, 14, 16, 18, 20
Mix data type in an array
#!/usr/bin/perl -w
use strict;
my $test = 30;
print
"Here is a list containing strings, (this one) ",
"numbers (",
3.6,
") and variables: ",
$test,
"\n"
;
Mixed Data Assigned to Array Cells
#!/usr/local/bin/perl
$i = 0;
$mixedData[$i] = \@mixedData;
$mixedData[2] = 8;
$mixedData[6] = "last cell";
$mixedData[4] = 3.4;
foreach $value (@mixedData){
print "Cell number $i = $value \n";
$i++;
}
print "\n\n";
print "The last cell of the array mixedData is $#mixedData";
print "\n\n";
Mixed Lists
#!/usr/bin/perl
use warnings;
use strict;
my $test = 30;
print
"strings",
"numbers (",
3.6,
") and variables: ",
$test,
"\n"
;
Modify individual elements, using the syntax ${$reference}[$element]:
#!/usr/bin/perl
use warnings;
use strict;
my @array = (8, 1, 4, 11, 17);
my $ref = \@array;
${$ref}[0] = 100;
print "Array is now : @array\n";
Months Of The Year
#!/usr/bin/perl
use warnings;
use strict;
my $month = 3;
print qw(January February March April May June July August September October November December)[$month];
Mulitple indexing
#!/usr/bin/perl -w
use strict;
my $mone;
my $mtwo;
($mone, $mtwo) = (1, 3);
print (("A ", "B ", "C ", "D ")[$mone, $mtwo]);
print "\n";
Multidimensional Arrays(Lists of Lists)
# A two-dimensional array consisting of 4 rows and 3 columns
@matrix=( [ 3 , 4, 0 ], # Each row is an unnamed list
[ 2, 7, 2 ],
[ 0, 3, 4 ],
[ 6, 5, 9 ],
) ;
print "@matrix\n";
print "Row 0, column 0 is $matrix[0][0].\n";
print $matrix[0]->[0];
print "Row 1, column 0 is $matrix[1][0].\n";
print $matrix[1]->[0];
for($i=0; $i < 4; $i++){
for($x=0; $x < 3; $x++){
print "$matrix[$i][$x] ";
}
print "\n";
}
Multiple Elements Of A List
#!/usr/bin/perl
use warnings;
use strict;
my $mone; my $mtwo;
($mone, $mtwo) = (1, 3);
print (("heads ", "shoulders ", "knees ", "toes ")[$mone, $mtwo]);
print "\n";
Numeric sort
#!/usr/bin/perl
use strict;
use warnings;
sub numerically {
$a*1.0 <=> $b*1.0 or $a cmp $b
};
my @words = qw(1e2 2e1 3 4 5);
print 'Normal sort: ', join(', ', sort @words), "\n";
print 'Numeric sort: ', join(', ', sort numerically @words), "\n";
Output all elements in an array with print command
@array = (1, 2, 3);
print @array;
Output nested array
#!/usr/bin/perl
use warnings;
use strict;
my @outer = (['a1', 'a2', 'a3'], ['b1', 'b2', 'b3'], ['c1', 'c2', 'c3']);
foreach my $outer_el (@outer) {
foreach (@{$outer_el}) {
print "$_\n";
}
print "\n";
}
Output the last element in the array
@array = qw( zero one two three four five six seven eight nine );
print "\@array[ $#array ] is $array[ $#array ].\n\n";
Output the number of elements and the last index number
@array = qw( zero one two three four five six seven eight nine );
print "There are ", scalar( @array ), " elements in \@array.\n";
print "The last index in \@array is $#array.\n\n";
Output the value of an array reference
#!/usr/bin/perl
use strict;
use warnings;
my @array = qw( A B C D E );
my $arrayReference = \@array;
print( "@$arrayReference\n" );
Output the whole array in print
@array = ("one", "two", "three");
print "Here is the array: ", @array, ".\n";
Output two -dimensional array
#!/usr/bin/perl
use warnings;
use strict;
my @array;
my @array2 = (
[ 1, 2, 3, 4 ],
[ 2, 3, 4, 5 ],
[ 3, 4, 5, 6 ],
[ 4, 5, 6, 7 ]
);
my $array3 = [
[ 1, 2, 3, 4 ],
[ 2, 3, 4, 5 ],
[ 3, 4, 5, 6 ],
[ 4, 5, 6, 7 ]
];
foreach ( 0 .. $#array ) {
print( "@{ $array[ $_ ] }\n" );
}
print( "\n" );
foreach my $row ( @array2 ) {
print( "@$row\n" );
}
print( "\n$array3->[ 2 ][ 2 ]\n" );
Paper Stacks
#!/usr/bin/perl
use warnings;
use strict;
my $hand;
my @pileofpaper = ("A", "B", "C", "D");
print "@pileofpaper\n";
$hand = pop @pileofpaper;
print "$hand\n";
$hand = pop @pileofpaper;
print "$hand.\n";
print "@pileofpaper\n";
pop @pileofpaper;
print "$hand\n";
push @pileofpaper, $hand;
push @pileofpaper, "E", "F";
print "@pileofpaper\n";
Pass user-defined function to sort function
@array = (6, 5, 4, 3, 2, 1);
sub myfunction
{
return (shift(@_) <=> shift(@_));
}
print join(", ", sort {myfunction($a, $b)} @array);
Perform list assignments and display results
@array = qw( zero one two three four five six seven eight nine );
print "@array\n\n";
( $chiquita , $dole ) = ( "banana", "pineapple" );
print "\$chiquita = $chiquita\n\$dole = $dole\n";
@array[ 1, 3, 5, 7, 9 ] = qw( 1 3 5 7 9 );
print "@array\n\n";
Place scalar variables in lists and arrays.
#!/usr/bin/perl -w
$element = "Ouch";
@array = ($element, 1, 2, 3, 4);
print "@array\n";
Pop value out of array
#!C:/perl/bin
@passengerships = ('T', 'O', 'B');
print "\n\n@passengerships \n\n"; #print the array values
push(@passengerships, "QE2"); # add another ship
print "@passengerships \n"; # print the array values again
$poppedstring = pop(@passengerships);
print "$poppedstring\n"; # This is the value we popped!
print "@passengerships \n"; # print the array values again
Print an element in a list of variables
#!/usr/bin/perl
print "Content-Type: text/html \n\n";
# This script demonstrates how to print an element in an array
@AcmeCars = ("Ford","Dodge","Chevy");
print "<p>* $AcmeCars[0] * is the first element
in the text array.</p>";
print "<p>* $AcmeCars[2] * is the third element
in the text array.</p>";
Print each value in the array.
foreach $Index (0..9) {
print "The cube of ", $Index + 1, " is $Array[$Index]\n";
}
Print function with sort and customized sorting function
print sort {$a cmp $b} ("c", "b", "a");
Print function with sort and customized sorting function in a descending order
print sort {$b cmp $a} ("c", "b", "a");
print "@{[uc(hello)]} there.\n";
print "@{[uc(hello)]} there.\n";
Program to demonstrate a pointer to a two-dimensional array
#!/bin/perl
my $matrix = [
[ 0, 2, 4 ],
[ 4, 1, 2 ],
[ 2, 5, 7 ]
] ;
print "$matrix->[2]->[1].\n";
for($x=0;$x<3;$x++){
for($y=0;$y<3;$y++){
print "$matrix->[$x]->[$y] ";
}
print "\n\n";
}
for($i = 0; $i < 3; $i++){
print "@{$matrix->[$i]}", "\n\n";
}
$p=\$matrix; # Reference to a reference
print ${$p}->[1][2], "\n";
Push array and join
#!/usr/bin/perl
use warnings;
use strict;
my $max = 6;
my @array = (1..$max);
while (my $element = shift @array) {
push (@array,$max - $element);
print $element, " : ", join(",", @array), "\n";
}
Push array into an array
for $loopindex (0..4) {
push @array, [1, 1, 1, 1];
}
print $array[0][0];
Push one array to another array
@a1 = (1, 2, 3);
@a2 = (4, 5, 6);
push (@a1, @a2);
print join (", ", @a1);
Push, pop, shift and unshift an array
#!/usr/bin/perl
use strict;
use warnings;
my @array = (1, 2, 3, 4, 5, 6);
push @array, '7';
print "@array\n";
my $last = pop @array;
print "$last\n";
unshift @array, -1, 0;
print "@array\n";
shift @array;
shift @array;
print "@array\n";
Push value from one array to another array
#!/usr/bin/perl
use warnings;
my @array = ("One", "Two", "Three", undef, "Five", "Six");
my @newarray = ();
foreach my $element (@array) {
last unless defined ($element);
push @newarray, $element;
}
foreach (@newarray) {
print $_." \n";
}
Push value into an array
push(@array, "one");
push(@array, "two");
push(@array, "three");
print $array;
Push value to an array
@a = (1 .. 10);
foreach (@a) {
if ($_ > 5) {
push @b, $_
}
};
print join(", ", @b);
Push value to array
#!C:/perl/bin
@passengerships = ('T', 'O', 'B');
print "\n\n@passengerships \n\n"; #print the array values
push(@passengerships, "QE2"); # add another ship
print "@passengerships \n"; # print the array values again
Put one array into another array as an element
#!/usr/bin/perl -w
use strict;
my @array1 = (1, 2, 3);
my @array2;
@array2 = (@array1, 4, 5, 6);
print "@array2\n";
Put one array into itself
#!/usr/bin/perl -w
use strict;
my @array2;
@array2 = (3, 5, 7, 9);
@array2 = (1, @array2, 11);
print "@array2\n";
$#questions is the index of the highest element in the @questions array.
#!/usr/bin/perl
use warnings;
use strict;
my @array = qw(alpha bravo charlie delta);
print "Scalar value : ", scalar @array, "\n";
print "Highest element: ", $#array, "\n";
Reducing the number of elements to 6
@array = qw( zero one two three four five six seven eight nine );
$#array = 5;
print "@array.\n";
Reference a dereferenced array by index
#!/usr/bin/perl -w
use strict;
my @band = qw(A B C D);
my $ref = \@band;
foreach (0..$#band) {
print "Array : ", $band[$_] , "\n";
print "Reference: ", ${$ref}[$_], "\n";
}
Reference array element by index
$variable1 = (a, b, c)[1];
print $variable1;
Reference Counting and Destruction
#!/usr/bin/perl
use warnings;
use strict;
my $ref;
{
my @array = (1, 2, 3);
$ref = \@array;
my $ref2 = \@array;
$ref2 = "Hello!";
}
undef $ref;
Reference more than one elements in an array at the same time
@a1 = (1, 2, 3, 4, 5, 6);
@a2 = @a1[0, 1, 2, 3];
print join (", ", @a2);
Reference negative array index
#!/usr/bin/perl -w
use strict;
print qw(
January February March
April May June
July August September
October November December
)[-1];
Reference single array element by using the $ not @
#!/usr/bin/perl -w
use strict;
my @array = (1, 3, 5, 7, 9);
print @array[1];
print $array[1];
References to Simulate Multi-Dimensional Arrays
$totalStores = 3;
$store = "asdfddddd";
for ($num = 1; $num <= $totalStores; $num++){
open (STOREINV, "$store${num}.txt");
my @store = <STOREINV>;
$allStores[$num] = \@store;
}
for ($x=1; $x<= $totalStores; $x++){
$invRef = $allStores[$x];
for ($i=0; $i <= $#$invRef; $i++){
print "$$invRef[$i] ";
}
print"\n";
}
Reference the outter array of an two dimensional array
@array = (
["A", "B"],
["C", "F", "G"],
["D", "E"],
);
for $loopindex (0..$#array) {
print join (", ", @{$array[$loopindex]}), "\n";
}
Reference two arrays in foreach statement
@array = (1, 2, 3);
@array2 = (4, 5, 6);
foreach $element (@array, @array2) {
print "$element\n";
}
Remove elements from array with splice
#!/usr/bin/perl
use strict;
use warnings;
my @array = ('a', 'b', 'c', 'd', 'e', 'f');
my @removed = splice @array, 2, 3;
print "@array\n";
print "@removed\n";
Remove elements from position 7 onward
#!/usr/bin/perl -w
@array = (1,2,3,4,5,6,7,8,9);
print "@array\n";
$offset = 7;
splice(@array, $offset);
Remove first element only and save it
#!/usr/bin/perl -w
@array = (1,2,3,4,5,6,7,8,9);
print "@array\n";
$offset = 0; # first element
$length = 1;
($first) = splice(@array, $offset, $length);
print "@array\n";
print "First element: $first\n";
Remove last three elements
#!/usr/bin/perl
use strict;
use warnings;
my @array = ('a', 'b', 'c', 'd', 'e', 'f');
my @last_3_elements = splice @array, -3;
print "@array\n";
print "@last_3_elements\n";
Removing 3 elements, beginning with element 15 of @array
@array = ( 0 .. 20 );
@array2 = ( A .. F );
print "\@array: @array\n";
print "\@array2: @array2\n\n";
@removed = splice( @array, 15, 3 );
print "removed: @removed\n",
"leaving: @array\n\n";
Removing all elements from element 8 to the end of @array
@array = ( 0 .. 20 );
@array2 = ( A .. F );
print "\@array: @array\n";
print "\@array2: @array2\n\n";
@chopped = splice( @array, 8 );
print "removed: @chopped\n",
"leaving: @array\n\n";
Removing all elements in the array
@array = qw( zero one two three four five six seven eight nine );
print "@array.\n";
print "There are now ", scalar( @array ),
" elements in \@array\n";
@array = ();
print "@array.\n";
print "There are now ", scalar( @array ),
" elements in \@array\n";
Replace the second and third elements.
# The splice function returns the elements it removes
#!/usr/bin/perl -w
@array = (1,2,3,4,5,6,7,8,9);
print "@array\n";
$offset = 1;
$length = 2; # two elements.
splice(@array, $offset, $length, 99, 98, 97, 96);
print "@array\n";
Replacing part of @array with the elements from @array2
@array = ( 0 .. 20 );
@array2 = ( A .. F );
print "\@array: @array\n";
print "\@array2: @array2\n\n";
@replaced = splice( @array, 5, scalar( @array2 ), @array2 );
print "replaced: @replaced\n",
"with: @array2\n",
"resulting in: @array\n\n";
Reverse an array and a list
@list = (90,89,78,100,87);
$str="Hello, world";
print "Original array: @list\n";4
print "Original string: $str\n";5
@revlist = reverse(@list);
$revstr = reverse($str);
print "Reversed array is: @revlist\n";
print "Reversed string is: $revstr\n";
$newstring = reverse(@list);
print "List reversed, context string: $newstring\n";
Reverse a sub-range of an array
@array = (1, 2, 3, 4, 5, 6);
@array[2 .. 4] = reverse @array[2 .. 4];
print join (", ", @array);
Running through Arrays
#!/usr/bin/perl
use warnings;
use strict;
my @array = qw(America Asia Europe Africa);
my $element;
for $element (@array) {
print $element, "\n";
}
Scalar Data in an Array
#!/usr/local/bin/perl
@FamilyName = ("Tom", "Michael", "A");
print $FamilyName[0];
print $FamilyName[1];
print $FamilyName[2];
print "\n\n";
print "$FamilyName[0] $FamilyName[1] $FamilyName[2]";
Shift and Unshift
#!/usr/bin/perl
use warnings;
use strict;
my @array = ();
unshift(@array, "first");
print "Array is now: @array\n";
unshift @array, "second", "third";
print "Array is now: @array\n";
shift @array ;
print "Array is now: @array\n";
shift array
#!/usr/bin/perl -w
use strict;
my @array = ();
unshift @array, "first";
print "Array is now: @array\n";
unshift @array, "second", "third";
print "Array is now: @array\n";
shift @array ;
print "Array is now: @array\n";
Shift value from array
@array = ("one", "two", "three");
$variable1 = shift(@array);
print $variable1;
Slice an array by referencing the index in a sub range
#!/usr/bin/perl -w
use strict;
my @sales = (126, 121, 129, 110, 113, 121, 112, 105, 716, 111, 118, 101);
my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
print "@months[3..5]\n@sales[3..5]\n";
Slicing out part of an array to make a sort of subarray
#!/usr/bin/perl -w
# Slicing an array.
@array = (1,2,3,'red');
# Get a slice of array.
@array[0,1,2] = ('green', 'blue', 'orange');
print "@array\n";
Sort an integer array
#!/usr/bin/perl -w
use strict;
my @unsorted = (1, 2, 11, 24, 3, 36, 40, 4);
my @sorted = sort @unsorted;
print "Sorted: @sorted\n";
Sort a string array
#!/usr/bin/perl -w
use strict;
my @unsorted = qw(A C B E D);
print "Unsorted: @unsorted\n";
my @sorted = sort @unsorted;
print "Sorted: @sorted\n";
Sort in action
#!/usr/bin/perl
use warnings;
use strict;
my @unsorted = qw(Co Cl Co Cr Co);
print "Unsorted: @unsorted\n";
my @sorted = sort @unsorted;
print "Sorted: @sorted\n";
Sorts
@names = (Cindy, Carol, Sherry, Tom, Jessica, Scott);
@names = reverse @names;
print "@names\n";
@numbers = reverse @numbers;
print "@numbers\n";
$names = reverse @names;
print "$names\n";
sub sortNumbers(){
$a <=> $b;
}
Special Scalars and Array Assignment
$#arrayname returns the number of the last subscript in the array.
$[ variable is the current array base subscript, zero.
@grades = (0,1,2,3,4);
print "The array is: @grades\n";
print "last index is $#grades\n";
$#grades=3;
print "The array is truncated to 4 elements: @grades\n";
@grades=();
print "The array is completely truncated: @grades\n";
splice(@array, 2, 0, "three");
@array = ("one", "two");
splice(@array, 2, 0, "three");
print join(", ", @array);
splice(@array, 2, 1, @array2);
@array = ("one", "two");
@array2 = ("two", "three", "four");
splice(@array, 2, 1, @array2);
print join(", ", @array);
Splice two arrays
@array = ("one", "two");
@array2 = ("three", "four");
splice(@array, 2, 0, @array2);
print join(", ", @array);
Splicing and replacing elements of a list
@colors=("red", "green", "purple", "blue", "brown");
print "The original array is @colors\n";
@lostcolors=splice(@colors, 2, 3, "yellow", "orange");
print "The removed items are @lostcolors\n";
print "The spliced array is now @colors\n";
Split a scalar to create a list
$string= "ABC:11/12/2009:10 St.:CA, value:012345";
@line=split(":", $string); # The string delimiter is a colon
print @line,"\n";
print "The guy's name is $line[0].\n";
print "The birthday is $line[1].\n\n";
@str=split(":", $string, 2);
print $str[0],"\n"; # The first element of the array
print $str[1],"\n"; # The rest of the array because limit is 2
print $str[2],"\n"; # Nothing is printed
@str=split(":", $string); # Limit not stated will be one more than total number of fields
print $str[0],"\n";
print $str[1],"\n";
print $str[2],"\n";
print $str[3],"\n";
print $str[4],"\n";
print $str[5],"\n";
( $name, $birth, $address )=split(":", $string);
print $name , "\n";
print $birth,"\n";
print $address,"\n";
$s = pop @{[@a]};
@a = (1, 2, 3);
$s = pop @{[@a]};
print "@a\n";
Store various type values in an array
#!c:/perl/bin
$title = "This is a title";
@things=('F', 16, 5.2, $title);
for($loopcount=0; $loopcount<4; $loopcount++)
{
print " (@things[$loopcount]) \n";
}
String array
#!/usr/bin/perl
use warnings;
use strict;
my @questions = qw(Java Python Perl C);
my @punchlines = ("A","B","D",'E');
print "Please enter a number between 1 and 4: ";
my $selection = <STDIN>;
$selection -= 1;
print "How many $questions[$selection] ";
print "programmers does it take to change a lightbulb?\n\n";
sleep 2;
print $punchlines[$selection], "\n";
Sum values in an array
@array = (1, 2, 3);
$running_sum = 0;
foreach $element (@array) {
$running_sum += $element;
}
print "Total = $running_sum";
The Array Size Indicator
$[ = 9999; #This loop doesn't run because @checksThisMonth returns the array size, which is less than 1501.
for ($i = $[; #initialization list
$i < @checksThisMonth; #conditional expression
$i++){ #increment list
print "$checksThisMonth[$i]";
}
#This loop runs because $#checksThisMonth returns the last cell index.
for ($i = $[; $i <= $#checksThisMonth; $i++){
print "$checksThisMonth[$i]";
}
The delete function removes a value from an element of an array but not the element itself.
The value deleted is simply undefined.
# Removing an array element
@colors=("red","green","blue","yellow");
print "@colors\n";
delete $colors[1]; # green is removed
print "@colors\n";
print $colors[1],"\n";
$size=@colors; # value is now undefined
print "The size of the array is $size.\n";
The join function joins the elements of an array into a single string
Format: join(DELIMITER, LIST)
# Joining each elements of a list with colons
$name="Tom";
$birth="11/12/2009";
$address="10 Main St.";
print join(":", $name, $birth, $address ), "\n";
The List Separator Variable
#!/usr/local/bin/perl
(@array) = (1..5, "A", "B", "C");
print STDOUT "@array\n\n";
print STDOUT "The behavior of array printing without quotes.\n";
print STDOUT @array;
print "\n\n";
The pop function pops off the last element of an array and returns it.
The array size is subsequently decreased by 1.
# Removing an element from the end of a list
@names=("A", "B", "C", "D");
print "@names\n";
$got = pop(@names);
print "$got\n";
print "@names\n";
The push function pushes values onto the end of an array, thereby increasing the length of the array.
# Adding elements to the end of a list
@names=("A", "B", "C", "D");
push(@names, "Jim", "Joseph", "Archie");
print "@names \n";
The reverse command reverses the order of the elements in a list, returning the new list.
#!/usr/bin/perl -w
@array = (1,2,3,'red');
print "Before: @array\n";
@array = reverse(@array);
print "After: @array\n";
The reverse function reverses the elements in an array
#Format:
#reverse(LIST)
#reverse LIST
# Reversing the elements of an array
@names=("B", "D", "T", "G");
print "@names \n";
@reversed=reverse(@names),"\n";
print "@reversed\n";
The shift function shifts off and returns the first element of an array, decreasing the size of the array by one element.
#If ARRAY is omitted, then the ARGV array is shifted, and, if in a subroutine, the @_ array is shifted.
# Removing elements from front of a list
@names=("Bob", "Dan", "Tom", "Guy");
$ret = shift @names;
print "@names\n";
print "The item shifted is $ret.\n";
The sort command sorts an array
#!/usr/bin/perl -w
@array = ('red', 'green', 'blue', 'orange', 'maroon');
print "Before: @array\n";
@sorted = sort(@array);
print "After: @sorted\n";
The sort function sorts and returns a sorted array.
#If SUBROUTINE is omitted, the sort is in string comparison order.
#If SUBROUTINE is specified, the first argument to sort is the name of the subroutine, followed by a list of values to be sorted.
#To sort data according to a locale, include the use locale pragma.
#Format:
#sort(SUBROUTINE LIST)
#sort(LIST)
#sort SUBROUTINE LIST
#sort LIST
# Simple alphabetic sort
@list=("Abc","Bcd", "Cde","Def" );
print "Original list: @list\n";
@sorted = sort(@list);
print "Ascii sort: @sorted\n";
# Reversed alphabetic sort
@sorted = reverse(sort(@list));
print "Reversed Ascii sort: @sorted\n";
The splice function removes and replaces elements in an array.
The LIST consists of new elements that are to replace the old ones.
Format:
splice(ARRAY, OFFSET, LENGTH, LIST)
splice(ARRAY, OFFSET, LENGTH)
splice(ARRAY, OFFSET)
# Splicing out elements of a list
@colors=("red", "green", "purple", "blue", "brown");
print "The original array is @colors\n";
@discarded = splice(@colors, 2, 2);
print "discarded are: @discarded.\n";
print "The spliced array is now @colors.\n";
The unshift function prepends LIST to the front of the array.
#Format: unshift(ARRAY, LIST)
# Putting new elements at the front of a list
@names=("Tom", "Bert", "Tom") ;
unshift(@names, "Liz", "Daniel");
print "@names\n";
Totalling a List
#!/usr/bin/perl
use warnings;
use strict;
total(1, 107, 105, 114, 9);
total(1...100);
sub total {
my $total = 0;
$total += $_ for @_;
print "The total is $total\n";
}
Two dimensional array is array of array
$array[0] = ["apples", "oranges"];
$array[1] = ["asparagus", "corn", "peas"];
$array[2] = ["ham", "chicken"];
print $array[1][1];
Two dimensional array is array scalar plus array
@{$array[0]} = ("apples", "oranges");
@{$array[1]} = ("asparagus", "corn", "peas");
@{$array[2]} = ("ham", "chicken");
print $array[1][1];
unshift array
#!/usr/bin/perl -w
use strict;
my @array = ();
unshift @array, "first";
print "Array is now: @array\n";
unshift @array, "second", "third";
print "Array is now: @array\n";
unshift places data to the front of an array
$num_elements = unshift(array, $prepend_data);
#!/usr/bin/perl -w
# Uses unshift with ARGV.
$prepend_data = "PREPENDED";
$num_elements = unshift(@ARGV, $prepend_data);
# Display arguments.
foreach $i (0 .. $#ARGV) {
print "$ARGV[$i]\n";
}
print "Total elements = $num_elements.\n";
Update part of an array by referencing only a sub range
#!/usr/bin/perl -w
use strict;
my @sales = (169, 118, 197, 110, 103, 101, 108, 105, 76, 111, 118, 101);
my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@sales[1..5] = (100, 101, 102, 103, 104);
print @sales
Use a scalar variable as our subscript:
#!/usr/bin/perl
use warnings;
use strict;
my @array = (1, 3, 5, 7, 9);
my $subscript = 3;
print $array[$subscript], "\n";
$array[$subscript] = 12;
use reverse on arrays as well as lists:
#!/usr/bin/perl
use warnings;
use strict;
my @count = (1..5);
for (reverse(@count)) {
print "$_...\n";
sleep 1;
}
print "BLAST OFF!\n";
'use strict' with two dimensional array
use strict vars;
$array = [
["A", "E"],
["B", "F", "G"],
["C", "D"],
];
print $array[0][0];
Using a $#array variable in a loop.
#!/usr/local/bin/perl
@myarray = ("testing", 98.6, "Olerud", 47);
for ($i = 0; $i <= $#myarray; $i++) {
print ("$myarray[$i]\n");
}
Using a minus variable as the array index
@a1 = (1, 2, 3);
print @a1[-2];
Using an Inline Function to Sort a Numeric List
# Sorting numbers with an unamed subroutine
@sorted_numbers= sort {$a <=> $b} (3,4,1,2);
print "The sorted numbers are: @sorted_numbers", ".\n";
Using @array as a condition
# When @array is empty, the condition becomes false; otherwise, it is true.
for ( $i = 1; $i <= 5; ++$i ) {
push( @array, $i );
print "@array\n";
}
while ( @array ) {
$firstTotal += pop( @array ); # remove last element
print "@array\n"; # display current @array
}
print "\$firstTotal = $firstTotal\n\n";
Using array length in for loop
@array = ("one", "two", "three");
for($loop_index = 0; $loop_index <= $#array; $loop_index++) {
print $array[$loop_index];
}
Using array operator to reference variable in an array
@a1 = (1, 2, 3, 4, 5, 6);
@a2 = @a1[0 .. 3];
print join (", ", @a2);
Using array reference to create two-dimensional array
@array1 = qw(apples oranges);
@array2 = qw(asparagus corn peas);
@array3 = qw(ham chicken);
$array[0] = \@array1;
$array[1] = \@array2;
$array[2] = \@array3;
print $array[1][1];
Using array reference to index the two dimensional array
@array = (
["apple", "orange"],
["asparagus", "corn", "peas"],
["ham", "chicken"],
);
$array1ref = $array[1];
print ${$array1ref}[1];
print ${array[1]}->[1];
print $array[1]->[1];
print $array[1][1];
Using array reference variable to get the element value
@array = (1, 2, 3);
$arrayref = \@array;
print @$arrayref[0];
print $arrayref->[0];
Using array reference with two-dimensional array
@array = (
["A", "F"],
["B", "E", "G"],
["C", "D"],
);
for $arrayreference (@array) {
print join (", ", @{$arrayreference}), "\n";
}
Using Arrays as an Indexed List
@months = qw (JUNK Jan Feb March April May June July Aug Sept Oct Nov Dec);
#assign the same values to the list @array.
@array = qw (a b c d e);
@array = ("a", "b", "c", "d", "e");
#For example, you could have set the @months array in the following fashion:
# $months[0] = "JUNK";
# $months[1] = "Jan";
# $months[2] = "Feb";
Using Arrays as Stacks
#!/usr/local/bin/perl -w
push (@myList, "Hello");
push (@myList, "World!");
push (@myList, "How");
push (@myList, "Are");
push (@myList, "You?");
while ( $index = pop(@myList) )
{
print "Popping off stack: $index\n";
}
Using array variable name as the reference to that array
@a = (1, 2, 3);
$arrayref = "a";
print "@$arrayref";
Using cmp in array sort customized function
#!/usr/bin/perl -w
use strict;
my @unsorted = (1, 2, 11, 24, 3, 36, 40, 4);
my @string = sort { $a cmp $b } @unsorted;
print "String sort: @string\n";
Using dereferenced array in foreach loop
#!/usr/bin/perl -w
use strict;
my @array = (2, 4, 6, 8, 10);
my $array_r = \@array;
foreach (@{$array_r}) {
print "An element: $_\n";
}
print "The highest index is $#{$array_r}\n";
print "This is what our reference looks like: $array_r\n";
Using foreach to change the value in an array
@a = (1 .. 10);
foreach (@a) {$_ *= 2;}
print join(", ", @a);
Using for each with $_ variable
@array = ("Hello ", "there.\n");
foreach $_ (@array) {
print $_;
}
Using for loop with array
@array = ("Hello ", "there.\n");
for (@array) {
print;
}
Using -> to reference value in an array reference variable
#!/usr/bin/perl
use strict;
use warnings;
my @array = qw( A B C D E );
my %hash = ( A => "AA",
B => "BB",
C => "CC",
D => "DD",
E => "EE" );
my $arrayReference = \@array;
my $hashReference = \%hash;
sub returnReference
{
return \@array;
}
print( "\$arrayReference->[ 1 ] = $arrayReference->[ 1 ]\n" );
Using join function to add separator
@array = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
print join(", ", @array);
Using <=> operator in array sort function
#!/usr/bin/perl -w
use strict;
my @unsorted = (1, 2, 11, 24, 3, 36, 40, 4);
my @number = sort { $a <=> $b } @unsorted;
print "Numeric sort: @number\n";
Using multi-dimensional array references.
#!/usr/bin/perl
$line = ['solid', 'black', ['1','2','3'] , ['4', '5', '6']];
print "\$line->[0] = $line->[0] \n";
print "\$line->[1] = $line->[1] \n";
print "\$line->[2][0] = $line->[2][0] \n";
print "\$line->[2][1] = $line->[2][1] \n";
print "\$line->[2][2] = $line->[2][2] \n";
print "\$line->[3][0] = $line->[3][0] \n";
print "\$line->[3][1] = $line->[3][1] \n";
print "\$line->[3][2] = $line->[3][2] \n";
print "\n"; # The obligatory output beautifier.
Using multi-dimensional array references again.
#!/usr/bin/perl
$line = ['solid', 'black', ['1','2','3', ['4', '5', '6']]];
print "\$line->[0] = $line->[0] \n";
print "\$line->[1] = $line->[1] \n";
print "\$line->[2][0] = $line->[2][0] \n";
print "\$line->[2][1] = $line->[2][1] \n";
print "\$line->[2][2] = $line->[2][2] \n";
print "\$line->[2][3][0] = $line->[2][3][0] \n";
print "\$line->[2][3][1] = $line->[2][3][1] \n";
print "\$line->[2][3][2] = $line->[2][3][2] \n";
print "\n";
Using negative subscripts to access elements from the end of the array
@array = qw( zero one two three four five six seven eight nine );
print "\@array[ -1 ] is $array[ -1 ].\n";
print "\@array[ -4 ] is $array[ -4 ].\n\n";
Using nested for loop to initialize two-dimensional array
for $outerloop (0..4) {
for $inerloop (0..4) {
$array[$outerloop][$innerloop] = 1;
}
}
print $array[0][0];
Using @ operator and one dimensioanal array to create two dimensioanl array
@{$array[0]} = ("apples", "oranges");
@{$array[1]} = ("asparagus", "corn", "peas");
@{$array[2]} = ("ham", "chicken");
print $array[1][1];
Using Pop to remove element from an array
for ( $i = 1; $i <= 5; ++$i ) {
push( @array, $i );
print "@array\n";
}
while ( @array ) {
$firstTotal += pop( @array ); # remove last element
print "@array\n"; # display current @array
}
print "\$firstTotal = $firstTotal\n\n";
Using push to insert elements at the end of @array
for ( $i = 1; $i <= 5; ++$i ) {
push( @array, $i ); # add $i to end of @array
print "@array\n"; # display current @array
}
Using qw to construct a string array
@array = qw(one two three);
Using reverse function in print statement
print reverse (1, 2, 3);
Using reverse in if statement
#!/usr/bin/perl -w
use strict;
my @count = (1..5);
foreach (reverse(@count)) {
print "$_...\n";
sleep 1;
}
print "BLAST OFF!\n";
Using reverse with and constant range
#!/usr/bin/perl -w
use strict;
print "Counting down (properly this time) : ", reverse(1 .. 6), "\n";
Using reverse with letter based range
#!/usr/bin/perl -w
use strict;
print "The other half (backwards): ", reverse('n' .. 'z'), "\n";
Using scalar function to get the array length
@array = (1, 2, 3);
print "\@array has " . scalar(@array) . " elements.";
Using shift the get value out of an array
@a = (1 .. 10);
do {
$v = shift @a;
print "Current number: $v\n";
} while ($v < 5);
Using sort function in print statement
print sort ("c", "b", "a");
Using splice to delete words.
#!/usr/local/bin/perl
while ($line = <STDIN>) {
@words = split(/\s+/, $line);
$i = 0;
while (defined($words[$i])) {
if (length($words[$i]) > 5) {
splice(@words, $i, 1);
} else {
$i++;
}
}
$line = join (" ", @words);
print ("$line\n");
}
Using splice to insert array elements.
#!/usr/local/bin/perl
$count = 0;
while ($line = <STDIN>) {
chop ($line);
@words = split(/\s+/, $line);
$added = 0;
for ($i = 0; $i+$added < @words; $i++) {
if ($count > 0 && ($count + $i) % 10 == 0) {
splice (@words, $i+$added, 0,
$count + $i);
$added += 1;
}
}
$count += @words - $added;
$line = join (" ", @words);
print ("$line\n");
}
Using the backslash operator on arrays.
#!/usr/bin/perl
$pointer = \@ARGV;
printf "\n Pointer Address of ARGV = $pointer\n";
$i = scalar(@$pointer);
printf "\n Number of arguments : $i \n";
$i = 0;
foreach (@$pointer) {
printf "$i : $$pointer[$i++]; \n";
}
Using the -> to reference the elements of a two-dimensional array
$array = [
["A", "F"],
["B", "E", "G"],
["C", "D"],
];
print $array->[1][1];
Using two-dimensional array
@array = (
[1, 2],
[3, 4],
);
print $array[1][1];
print $array[0][1];
print $array[1][0];
Using unshift to insert elements at the front of @array
for ( $i = 1; $i <= 5; ++$i ) {
push( @array, $i );
print "@array\n";
}
for ( $i = 1; $i <= 5; ++$i ) {
unshift( @array, $i ); # add $i to front of @array
print "@array\n"; # display current @array
}
While there are more elements in @array, remove each element with shift
for ( $i = 1; $i <= 5; ++$i ) {
push( @array, $i );
print "@array\n";
}
while ( @array ) {
$secondTotal += shift( @array ); # remove first element
print "@array\n"; # display current @array
}
print "\$secondTotal = $secondTotal\n";