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 Statement Program
A do statement.
#!/usr/local/bin/perl
$count = 1;
do {
print ("$count\n");
$count++;
} until ($count > 5);
Analysis of sales results
$metQuota = 0;
$didNotMeetQuota = 0;
$employeeCounter = 1;
while ( $employeeCounter <= 10 ) {
print "Enter quota result, (yes or no): ";
chomp( $result = <STDIN> );
$result eq 'yes' ? ++$metQuota : ++$didNotMeetQuota;
$employeeCounter++;
}
print "\nMet quota: $metQuota\n";
print "Failed to meet quota: $didNotMeetQuota\n";
if ( $metQuota > 8 ) {
print "Raise holiday bonuses!\n";
}
A program containing a simple example of an if statement.
#!/usr/local/bin/perl
print ("Enter a number:\n");
$number = <STDIN>;
chop ($number);
if ($number) {
print ("The number is not zero.\n");
}
print ("This is the last line of the program.\n");
A program that demonstrates the while statement.
#!/usr/local/bin/perl
$done = 0;
$count = 1;
print ("This line is printed before the loop starts.\n");
while ($done == 0) {
print ("The value of count is ", $count, "\n");
if ($count == 3) {
$done = 1;
}
$count = $count + 1;
}
print ("End of loop.\n");
A program that loops using a single-line conditional statement.
#!/usr/local/bin/perl
$count = 0;
print ("$count\n") while ($count++ < 5);
A program that prints the numbers from 1 to 5 using the for statement.
#!/usr/local/bin/perl
for ($count=1; $count <= 5; $count++) {
print ("$count\n");
}
A program that uses the if-else statement.
#!/usr/local/bin/perl
print ("Enter a number:\n");
$number1 = <STDIN>;
chop ($number1);
print ("Enter another number:\n");
$number2 = <STDIN>;
chop ($number2);
if ($number1 == $number2) {
print ("The two numbers are equal.\n");
} else {
print ("The two numbers are not equal.\n");
}
print ("This is the last line of the program.\n");
A program that uses the if-elsif-else statement.
#!/usr/local/bin/perl
print ("Enter a number:\n");
$number1 = <STDIN>;
chop ($number1);
print ("Enter another number:\n");
$number2 = <STDIN>;
chop ($number2);
if ($number1 == $number2) {
print ("The two numbers are equal.\n");
} elsif ($number1 == $number2 + 1) {
print ("The first number is greater by one.\n");
} elsif ($number1 + 1 == $number2) {
print ("The second number is greater by one.\n");
} else {
print ("The two numbers are not equal.\n");
}
print ("This is the last line of the program.\n");
A program that uses the until statement.
#!/usr/local/bin/perl
print ("What is 17 plus 26?\n");
$correct_answer = 43; # the correct answer
$input_answer = <STDIN>;
chop ($input_answer);
until ($input_answer == $correct_answer) {
print ("Wrong! Keep trying!\n");
$input_answer = <STDIN>;
chop ($input_answer);
}
print ("You've got it!\n");
Average-sales problem with counter-controlled repetition
$total = 0;
$weekCounter = 1;
while ( $weekCounter <= 5 ) {
print "Enter sales for week $weekCounter: ";
chomp( $sales = <STDIN> );
$total += $sales;
++$weekCounter;
}
$average = $total / 5;
print "\nSales averaged $average computers per week\n";
Average-sales problem with sentinel-controlled repetition
$total = 0;
$weekCounter = 0;
print "Enter sales for week or enter quit: ";
chomp( $sales = <STDIN> );
until ( $sales eq 'quit' ) {
$weekCounter++;
$total += $sales;
print "Enter sales for week or enter quit: ";
chomp( $sales = <STDIN> );
}
if ( $weekCounter != 0 ) {
$average = $total / $weekCounter;
print "\nSales averaged $average computers per week.\n";
}
else {
print "\nNo sales figures were entered.\n";
}
A while loop is often used to read from a file until there is no more data available.
#!/usr/local/bin/perl
# Set the value of x
$x=1;
while ($x <= 10)
{
print $x++ . ", ";
}
print "\n";
A word-counting program that uses the next statement.
#!/usr/local/bin/perl
$total = 0;
while ($line = <STDIN>) {
$line =~ s/^[\t ]*//;
$line =~ s/[\t ]*\n$//;
next if ($line eq "");
@words = split(/[\t ]+/, $line);
$total += @words;
}
print ("The total number of words is $total\n");
A word-counting program that uses the redo statement.
#!/usr/local/bin/perl
$total = 0;
for ($count = 1; $count <= 3; $count++) {
$line = <STDIN>;
last if ($line eq "");
$line =~ s/^[\t ]*//;
$line =~ s/[\t ]*\n$//;
redo if ($line eq "");
@words = split(/[\t ]+/, $line);
$total += @words;
}
print ("The total number of words is $total\n");
Breaking Out
#!/usr/bin/perl
use warnings;
use strict;
while (<STDIN>) {
chomp;
last unless $_;
my $sdrawkcab = reverse $_;
print "$sdrawkcab\n";
}
Choosing an Iterator
#!/usr/bin/perl
use warnings;
use strict;
my @array = (1, 3, 5, 7, 9);
foreach my $i (@array) {
print "This element: $i\n";
}
Conditional Control Statements
# if (Expression) {Code Segment}
# if (Expression) {Code Segment} else {Code Segment}
# if (Expression) {Code Segment} elsif {Code Segment} ... else {Code Segment}
#!/usr/local/bin/perl -w
while (<STDIN>)
{
chomp;
if ($_ < 10)
{
print "$_ is less than 10.\n";
}
elsif ($_ < 20)
{
print "$_ is between the values of 10 and 19.\n";
}
else
{
print "$_ is greater than or equal to 20.\n";
}
}
Conditional Modifiers and print
$_ = "xabcy\n";
print if /abc/;# Could be written: print $_ if $_ =~ /abc/;
Conditional Modifiers: The if Modifier
Format: Expression2 if Expression1;
$x = 5;
print $x if $x == 5;
Conditional operator: The unless Modifier
# Format: Expression2 unless Expression1;
$x=5;
print $x unless $x == 6;
Conditional operator: The unless Modifier and while loop and __DATA__
while(<DATA>){
print unless /N/; # Print line if it doesn't match N
}
__DATA__
A
B
I
N
J
K
Controlling Loop Flow
#!/usr/bin/perl
use warnings;
use strict;
my $stopnow = 0;
until ($stopnow) {
$_ = <STDIN>;
chomp;
if ($_) {
my $sdrawkcab = reverse $_;
print "$sdrawkcab\n";
} else {
$stopnow = 1;
}
}
print "!enod llA\n";
Count 10 with while loop
#!/usr/bin/perl
use warnings;
use strict;
# count from 1 to 10 (note the post-increment in the condition)
my $n = 0;
while ($n++ < 10) {
print $n, "\n";
}
Counting Up And Down
#!/usr/bin/perl
use warnings;
use strict;
print "Counting up: ", (1 .. 6), "\n";
print "Counting down: ", (6 .. 1), "\n";
print "Counting down (properly this time) : ", reverse(1 .. 6), "\n";
print "Half the alphabet: ", ('a' .. 'm'), "\n";
print "The other half (backwards): ", reverse('n' .. 'z'), "\n";
Create an infinite loop using a for loop:
#!/usr/local/bin/perl -w
for (;;)
{
print "This is the loop that never ends...\n";
}
Declare variable in foreach statement
#!/usr/bin/perl -w
use strict;
my @array = (1, 3, 5, 7, 9);
foreach my $i (@array) {
print "This element: $i\n";
}
Demonstrating the .. operator
@array2 = ( 1 .. 5 );
print "Value\tRunning Total\n";
for ( $i = 0; $i < 5; ++$i ) {
$total += $array2[ $i ];
print( $array2[ $i ], "\t$total\n");
}
@array2 = ( 'a' .. 'z' );
print "\n@array2\n";
Do .. while statement
#!/usr/bin/perl -w
use strict;
my $i = 1;
print "starting do...while:\n";
do {
print " the value of \$i: $i\n";
$i++;
} while ($i < 6);
Duplicate of the foreach structure with for structure
for $letter ( 'A' .. 'G' ) {
print "$letter";
}
print "\n";
foreach $letter ( 'A' .. 'G' ) {
print "$letter";
}
Duplicate the for structure with the foreach keyword
foreach ( $number = 0; $number <= 20; $number += 5 ) {
print "$number ";
}
print "\n";
Each time through the loop, foreach places the next element of the list into the scalar variable.
#!/usr/bin/perl -w
@languages = ("A","C","D","B","A");
foreach $lang (@languages) {
if ($lang eq "Perl") {
print "Perl is $lang.\n";
} else {
print "$lang ideas.\n";
}
}
Example of foreach from a min to a max.
#!/usr/bin/perl -w
foreach $i (5..10) {
print "$i\n";
}
Example using the continue block
#! /usr/bin/perl#
for ($i=1; $i<=10; $i++) {
if ($i==5){
print "\$i == $i\n";
next;
}
print "$i ";
}
Exit a loop
$Pattern = "perl";
$File = "myfile";
open (FILE,$File) || die "Can't open $File, $!\n";
while(<FILE>) {
if (/$Pattern/o) {
print "$File: $_";
last;
}
}
close(FILE);
Exits using the last statement.
#!/usr/local/bin/perl
$total = 0;
while (1) {
$line = <STDIN>;
if ($line eq "") {
last;
}
chop ($line);
@numbers = split (/[\t ]+/, $line);
foreach $number (@numbers) {
if ($number =~ /[^0-9]/) {
print STDERR ("$number is not a number\n");
}
$total += $number;
}
}
print ("The total is $total.\n");
Extend the if statement to include an else block
$lang = <STDIN>;
chomp($lang);
if ( $lang eq "perl" ) {
print "Congratulations, you choose perl!\n";
} elsif ( $lang eq "Tcl" ) {
print "Tcl is great, too.\n";
} else {
print "Well, use $lang if you feel ";
}
foreach ( 1 .. 10 ) : loops 10 times, not requiring a control variable
foreach ( 1 .. 10 ) {
print "*";
}
foreach (1 .. 10) range
foreach (1 .. 10) {
print;
}
foreach and array
#!/usr/bin/perl
$str="hello";
@numbers = (1, 3, 5, 7, 9);
print "\$str is initially $str.\n";
print "\@numbers is initially @numbers.\n";
foreach $str (@numbers ){
$str+=5;
print "$str\n";
}
print "Out of the loop--\$str is $str.\n";
print "Out of the loop--The array \@numbers is now @numbers.\n";
foreach Loop Array Processing
#!/usr/local/bin/perl
@digits = (1..10);
foreach $number (@digits){
print $number;
$number += 10;
}
print "\n\n@digits";
foreach Loop Hash Processing
#!/usr/local/bin/perl
print " SORTED INDEXES OF THE HASH %ENV \n";
foreach $key (sort (keys %ENV)){
print "key = $key and retrieves: $ENV{$key}\n";
}
print "\n SORTED VALUES OF THE HASH %ENV \n";
foreach $value (sort (values %ENV)){
print "value = $value}\n";
}
foreach Loop Hash Processing in a CGI Program
#!/usr/bin/perl
print<<'eof';
Content-Type: text/html
<html>
<head><title>CGI Environment Variables</title></head>
<body>
eof
foreach $index (keys %ENV){
print "$index => $ENV{$index} <br>";
}
print<<'eof';
</body>
</html>
eof
For each loop with array
#!/usr/bin/perl
use warnings;
@array = ("one", "two", "three");
foreach $iterator (@array) {
print "The value of the iterator is now $iterator \n";
}
For each loop with array and $_
#!/usr/bin/perl
@array = ("one", "two", "three", "four");
foreach (@array) {
print "The value of the iterator is now $_ \n";
}
foreach statement.
#!/usr/local/bin/perl
@words = ("Here", "is", "a", "list.");
foreach $word (@words) {
print ("$word\n");
}
foreach statement with number range
#!/usr/bin/perl -w
use strict;
my $number;
foreach $number (1 .. 10) {
print "the number is: $number\n";
}
From to
#!/usr/bin/perl
use warnings;
use strict;
my $start = 2;
my $end = 4;
while (<>) {
($. == $start)..($. == $end) and print "$.: $_";
}
Going onto the Next
#!/usr/bin/perl
use strict;
use warnings;
my @array = (8, 3, 0, 2, 2, 0);
for (@array) {
if ($_ == 0) {
print "Skipping zero element.\n";
next;
}
print "48 over $_ is ", 48/$_, "\n";
}
Goto statement with label
INPUT: $line = <>;
if ($line !~ /exit/) {
print "Try again\n";
goto INPUT
}
Here is an example of the for loop
#!C:/perl/bin
for($linenumber = 1; $linenumber < 10; $linenumber++)
{
print "Perl Fast & Easy \n";
}
If and else
#!/usr/bin/perl
$input=<>;
if ($input >= 5 ) {
print "The input number is equal to or greater than 5 \n";
} else {
print "The input number is less than 5 \n";
}
if/else statement
#if ( expression ){
# statements;
#else{
# statements;
#}
$coin = int (rand(2 )) + 1; # Generate a random number between 1 and 2
if( $coin == 1 ) {
print "HEAD\n";
}
else {
print "TAIL\n";
}
if/elsif statement
#if ( expression ){
# statements;
#elsif ( expression ){
# statements;
#}
#elsif (expression){
# statements;
#else{
# statements;
#}
$day_of_week = int(rand(7)) + 1;
print "Today is: $day_of_week\n";
if ( $day_of_week >=1 && $day_of_week <=4 ) {
print "from 9 am to 9 pm\n";
}
elsif ( $day_of_week == 5) {
print "from 9 am to 6 pm\n";
}
else {
print "weekends\n";
}
if in a while loop
$i=1;
while ($i <= 10){
if ($i==5){
print "\$i == $i\n";
$i++;
next;
}
print "$i ";
$i++;
}
if scope
#!/usr/bin/perl
use strict;
use warnings;
if ( (my $toss=rand) > 0.5 ) {
print "Heads ($toss)\n";
} else {
print "Tails ($toss)\n";
}
If start with - no repeat
NUMBER: while (<>) {
next NUMBER if /^-/;
print;
}
if statement
#if ( expression ){
# statements;
#}
# Example
$a = 0;
$b = 4;
if ( $a == $b ){ print "$a is equal to $b"; }
If statement and integer comparsion
#!C:/Perl/Bin
$number = 5;
if ($number = 5)
{
print "\n\n\$number is equal to 5\n\n";
}
If statement in a while statement
while (<>) {
print "Too big!\n" if $_ > 100;
}
If statement ladder
$variable = 2;
if ($variable == 1) {
print "Yes, it's one.\n";
} elsif ($variable == 2) {
print "Yes, it's two.\n";
} elsif ($variable == 3) {
print "Yes, it's three.\n";
} elsif ($variable == 4) {
print "Yes, it's four.\n";
} elsif ($variable == 5) {
print "Yes, it's five.\n";
} else {
print "Sorry, can't match it!\n";
}
If statement with else
$variable = 5;
if ($variable == 5) {
print "Yes, it's five.\n";
}
else
{
print "No, it's not five.\n";
}
If statement with scalar variable
$variable = 5;
if ($variable == 5) {
print "Yes, it's five.\n";
} else {
print "No, it's not five.\n";
}
If you declare your iterator outside the loop, any value it had then will be restored afterwards.
#!/usr/bin/perl
use warnings;
use strict;
my @array = (1, 3, 5, 7, 9);
my $i="Hello there";
foreach $i (@array) {
print "This element: $i\n";
}
print "All done: $i\n";
Initialization, test, and increment, decrement of counters is done in one step
#!/usr/bin/perl
for ($i=1, $total=10, $remain=$total, $where="on the shelf";$i <= $total; $i++, $remain--){
if ($remain == 1){
print "$remain bottle of beer $where" ;
}else {
print "$remain bottles of beer $where.";
}
print "Now ", $total - $i , " bottles of beer $where!\n";
if ($i == 10 ){
print "Party's over.\n";
}
}
Labels: Create an infinite loop to demonstrate how last will break out of multiple code blocks.
#!/usr/local/bin/perl -w
# Define the label name.
EXIT:
{
for (;;)
{
my $x = 0;
for (;;$x++)
{
print "$x, \n";
last EXIT if $x >= 5;
}
}
}
print "Out of for loops.\n";
last if
#!/usr/bin/perl -w
use strict;
while (<STDIN>) {
last if $_ eq "done\n";
print "You entered: $_";
}
print "All done!\n";
last statement
FOREVER: for (;;) {
chomp($line = <>);
if ($line eq 'q') {
last FOREVER;
} else {
print "You typed: $line\n";
}
}
last statement inside an if statement
#!/usr/bin/perl -w
use strict;
while (<STDIN>) {
if ($_ eq "done\n") {
last;
}
print "You entered: $_";
}
print "All done!\n";
Last with label
#!/usr/bin/perl -w
use strict;
my $i = 1;
OUTER: while ($i <= 5) {
my $j = 1;
while ($j <= 5) {
last OUTER if $j == 3;
print "$i ** $j = ", $i ** $j, "\n";
$j++;
}
$i++;
}
Letter based range
#!c:/perl/bin
@alphabet = (a..z);
for($loopcount=0; $loopcount<27; $loopcount++)
{
print "@alphabet[$loopcount] \n";
}
Loop Control Statements
#!/usr/local/bin/perl -w
for ($x=1; $x <= 10; $x++)
{
print $x . ", ";
}
print "\n";
Looping Modifiers: The while Modifier
#Format: Expression2 while Expression1;
$x=1;
print $x++,"\n" while $x != 5;
Looping through an array with the for repetition structure
@array = ( "Hello", 283, "there", 16.439 );
for ( $i = 0; $i < 4; ++$i ) {
print "$i$array[ $i ]\n";
}
Looping Until
#!/usr/bin/perl
use warnings;
use strict;
my $countdown = 5;
until ($countdown-- == 0) {
print "Counting down: $countdown\n";
}
Looping While
#!/usr/bin/perl
use warnings;
use strict;
my $countdown = 5;
while ($countdown > 0) {
print "Counting down: $countdown\n";
$countdown--;
}
Loop with label
#!/usr/bin/perl -w
use strict;
my $i = 1;
while ($i <= 5) {
my $j = 1;
while ($j <= 5) {
last if $j == 3;
print "$i ** $j = ", $i ** $j, "\n";
$j++;
}
$i++;
}
Mix $_ and foreach statement
#!/usr/bin/perl -w
use strict;
my @a = qw(hello world good bye);
print "[$_]\n" foreach @a;
Mixed diamond operator with for loop condition
for (print "Type q to quit.\n"; <> ne "q\n"; print
"Don't you want to quit?\n") {}
Mixed diamond operator with for loop condition 2
for (print "%"; <>; print "%") {
print;
}
Nested for loop
for ($rows=5; $rows>=1; $rows--){
for ($columns=1; $columns<=$rows; $columns++){
printf "*";
}
print "\n";
}
Nest if statement into for loop
#!C:/perl/bin
for($number = 1; $number <= 3; $number++)
{
print "\nLoop number: $number";
if ($number < 2)
{
print "\n\$number is less than 2\n\n";
}
elsif ($number > 2)
{
print "\n\$number is greater than 2\n\n";
}
else
{
print "\n\n\$number equals 2\n\n";
}
}
Next if
#!/usr/bin/perl -w
use strict;
print "Please enter some text:\n";
while (<STDIN>) {
next if $_ eq "\n";
chomp;
print "You entered: [$_]\n";
}
Next statement
#!/usr/bin/perl -w
use strict;
print "Please enter some text:\n";
while (<STDIN>) {
if ($_ eq "\n") {
next;
}
chomp;
print "You entered: [$_]\n";
}
Next statement with if statement
@a = (0 .. 20);
@b = (-10 .. 10);
DIVISION: while (@a) {
$a = pop @a;
$b = pop @b;
next DIVISION if ($b == 0);
print "$a / $b = " . $a / $b . "\n";
}
next with condition
while ($loop_index <= 10) {
print "Hello\n";
next if $loop_index > 5;
print "there\n";
} continue {
$loop_index++;
}
@numbers = ( 1 .. 10 );
print "\@numbers: @numbers\n\n";
Perl has a number of string comparison operators you can use in if statements.
Perl Usage
eq Equal
ge Greater than or equal to
gt Greater than
le Less than or equal to
lt Less than
ne Not equal
cmp Returns -1 if less than, 0 if equal and 1 if greater than
Plural format and ternary operator
#!/usr/bin/perl
use warnings;
use strict;
my @words = split ('\s+', <>); #read some text and split on whitespace
my $words = scalar (@words);
print "There ", ($words == 1)?"is":"are"," $words word", ($words == 1)?"":"s"," in the text \n";
Plural message
#!/usr/bin/perl
use warnings;
use strict;
my @words = split ('\s+', <>);
my $words = scalar (@words);
#ERROR!
my $message = "There ". ($words==1) ? "is" : "are". " $words word" . ($words == 1)?"" : "s". " in the text\n";
print $message;
Plural output with if statement
#!/usr/bin/perl
use warnings;
use strict;
my @words = split ('\s+', <>);
my $count = scalar (@words);
print "There ";
if ($count == 1) {
print "is";
} else {
print "are";
}
print " $count word";
unless ($count == 1) {
print "s";
}
print " in the text \n";
Print out even numbers with a do...while loop
#!/usr/bin/perl
use warnings;
use strict;
my $n = 0;
do {
{
next if ($n % 2);
print $n, "\n";
}
} while ($n++ < 10);
Put more than one statement first and third part of for statement
for ($loop_index = 0, $double = 0; $loop_index <= 10; $loop_index++, $double = 2 * $loop_index) {
print "Loop index " . $loop_index . " doubled equals " . $double . "\n";
}
Range based on letter
#!/usr/bin/perl -w
use strict;
print "Half the alphabet: ", ('a' .. 'm'), "\n";
Range based on letter and digit: from 3 to z
#!/usr/bin/perl -w
use strict;
print "Going from 3 to z: ", (3 .. 'z'), "\n";
Range based on letter and digit: from z to 3
#!/usr/bin/perl -w
use strict;
print "Going from z to 3: ", ('z' .. 3), "\n";
Range counting down
#!/usr/bin/perl -w
use strict;
print "Counting down: ", (6 .. 1), "\n";
Range counting up
#!/usr/bin/perl -w
use strict;
print "Counting up: ", (1 .. 6), "\n";
range list and for loop
#!c:/perl/bin
@months=(1..12);
for($loopcount=0; $loopcount<13; $loopcount++)
{
print "@months[$loopcount] \n";
}
Range Operator
print 0 .. 10,"\n";
@alpha=('A' .. 'Z');
print "@alpha";'
@a=('a'..'z', 'A'..'Z');
print "@a\n";'
@n=( -5 .. 20 );
print "@n\n";'
redo statement
#!/usr/bin/perl -w
use strict;
my $number = 10;
while (<STDIN>) {
chomp;
print "You entered: $_\n";
if ($_ == $number) {
$_++;
redo;
}
print "Going to read the next number now...\n";
}
Reference array length in for loop
#!/usr/bin/perl -w
use strict;
my @names = qw(A B C D);
print "processing using a for loop:\n";
for (my $i = 0; $i <= $#names; $i++) {
print " Hello $names[$i]!\n";
}
Reference for loop control variable
for ($loop_index = 1; $loop_index <= 10; $loop_index++) {
print "This is iteration number $loop_index\n";
}
Setting elements in a list to equal the corresponding elements of another list with three different names
#!/usr/bin/perl -w
($one, $two, $three) = (1..3);
print "$one $two $three\n";
Standard foreach structure, printing the values in a list
foreach $name ( 'A', 'J', 'S', 'D ' ) {
print "$name";
}
Standard foreach structure. Prints the letters A-G
foreach $letter ( 'A' .. 'G' ) {
print "$letter";
}
Standard for structure: Loops 5 times, printing the multiples of 5 from 0-20
for ( $number = 0; $number <= 20; $number += 5 ) {
print "$number ";
}
print "\n";
String based range
#!c:/perl/bin
@letters = (aa..dd);
for($loopcount=0; $loopcount<82; $loopcount++)
{
print " (@letters[$loopcount]) ";
}
Sums the numbers from 1 to a specified number and also sums the even numbers.
#!/usr/local/bin/perl
print ("Enter the last number in the sum:\n");
$limit = <STDIN>;
chop ($limit);
$count = 1;
$total = $eventotal = 0;
for ($count = 1; $count <= $limit; $count++) {
$total += $count;
if ($count % 2 == 1) {
# start the next iteration if the number is odd
next;
}
$eventotal += $count;
}
print("The sum of the numbers 1 to $limit is $total\n");
print("The sum of the even numbers is $eventotal\n");
Swich for data type
#!/usr/bin/perl
use strict;
use warnings;
use Switch;
my $perl = "Perl";
my %hash = ( "A" => 2, "B" => 3 );
my $cref = sub { $_[0] eq "C" };
sub testcase { $_[0] eq "D" };
my @array = (2..4);
my @values=qw[
1 perl Perl 3 6 pErl PerL pERL pERl peRL PERL php
];
foreach my $input (@values) {
switch ($input) {
case 1{ print "literal number" }
case "perl" { print "literal string" }
case ($perl){ print "string variable" }
case (\@array) { print "array variable reference" }
case [5..9] { print "literal array reference" }
case (%hash){ print "hash key" }
case { "PerL" => "Value" } { print "hash reference key" }
case { $_[0] eq "pERL" }{ print "anonymous sub" }
case ($cref){ print "anonymous code reference" }
case (\&testcase) { print "named code reference" }
case /^perl/i { print "regular expression" }
else { print "not known" }
}
print "\n";
}
Switch on sub
#!/usr/bin/perl -w
use strict;
use Switch;
my $input;
sub lessthan { $input < $_[0] };
$input=int(<>);
switch ( \&lessthan ) {
case 10 { print "less than 10\n" }
case (100-$input) { print "less than 50\n" }
case 100 { print "less than 100\n" }
}
$_ takes the place of the control variable
foreach ( 'A ', 'J ', 'S ', 'D ' ) {
print "$_";
}
The continue block allows the while loop to act like a for loop
$i=1;
while ($i <= 10) {
if ($i == 5) {
print "\$i == $i\n";
next;
}
print "$i ";
}continue {$i++;} # $i is incremented only once
The continue block gets executed just before the condition gets evaluated again
#while (condition) {
# # ...
#} continue {
# # ..
#}
#!/usr/bin/perl -w
$i = 0;
while ($i < 10) {
print "Iteration $i.\n";
} continue {
$i++;
}
The do/while and do/until Loops
#!/usr/bin/perl
$x = 1;
do {
print "$x ";
$x++;
} while ($x <= 10);
print "\n";
$y = 1;
do {
print "$y " ;
$y++;
} until ($y > 10);
The foreach Loop
#Format:
#foreach VARIABLE (ARRAY)
#{BLOCK}
#!/usr/bin/perl
foreach $pal ('A', 'B', 'H', 'P') {
print "Hi $pal!\n";
}
The foreach modifier evaluates once for each element, with $_ aliased to each element
@alpha=(a .. z, "\n");
print foreach @alpha;
The foreach statement iterates through list values, assigning a variable the value of each element in turn.
#!/usr/local/bin/perl
# Create a list of the days of the week.
@days = qw (Monday Tuesday Wednesday Thursday Friday Saturday Sunday);
# Cycle through the loop, and print out the contents.
foreach $day (@days)
{
print "$day\n";
}
The foreach statement lets you iterate for each element in a list or array:
foreach variable (list) {
# ...
}
The for Loop
#Format: for (Expression1;Expression2;Expression3) {Block}
#The above format is equivalent to the following while statement:
#Expression1;
#while (Expression2)
# {Block; Expression3};
#!/usr/bin/perl
for ($i=0; $i<10; $i++){# Initialize, test, and increment $i
print "$i ";
}
print "\nOut of the loop.\n";
The if Construct
print "How old are you? ";
chomp($age = <STDIN>);
if ($age >= 21 ){ # If true, enter the block
print "Let's party!\n";
}
print "You said you were $age.\n";
The if/else Construct
print "What version of the operating system are you using? ";
chomp($os=<STDIN>);
if ($os > 2) {
print "good!\n";
}
else {
print "Expect some problems.\n";
}
The if/elsif/else Construct
$hour=(localtime)[2];
if ($hour >= 0 && $hour < 12){
print "Good-morning!\n";
}elsif ($hour == 12){
print "Lunch time.\n";
}elsif ($hour > 12 && $hour < 17) {
print "Siesta time.\n";
}
else {
print "Goodnight. Sweet dreams.\n";
}
The last statement breaks out of a loop from within the loop block.
$n=0;
while( $n < 10 ){
print $n;
if ($n == 3){
last; # Break out of loop
}
$n++;
}
print "Out of the loop.<br>";
The .. operator goes from a minimum to a maximum, with foreach
#!/usr/bin/perl -w
foreach $i (5..10) {
print "$i\n";
}
The or part allows for a statement to be executed if the main part fails.
#!/usr/bin/perl -w
$filename = "nofile";
open(TMP, $filename) or die "Can't open \"$filename\"";
The Range Operator and Array Assignment
@digits=(0 .. 10);
@letters=( 'A' .. 'Z' );
@alpha=( 'A' .. 'Z', 'a' .. 'z' );
@n=( -5 .. 20 );
The range operator and foreach loop
foreach $hour (1 .. 24){
if ($hour > 0 && $hour < 12) {
print "Good-morning.\n";
}
elsif ($hour == 12) {
print "Happy Lunch.\n";
}
elsif ($hour > 12 && $hour < 17) {
print "Good afternoon.\n";
}
else {
print "Good-night.\n";
}
}
The Switch.pm Module
use Switch;
print "What is your favorite color? ";
chomp($color=<STDIN>);
switch("$color"){
case "red" { print "Red!\n"; }
case "blue" { print "blues.\n"; }
case "green" { print "green\n";}
case "yellow" { print "yellow";}
else { print "$color is not in our list.\n";}
}
print "Execution continues here....\n";
The unless Construct
print "How old are you? ";
chomp($age = <STDIN>);
unless ($age <= 21 ){ # If false, enter the block
print "Let's party!\n";
}
print "You said you were $age.\n";
The unless statement is the opposite of if and executes a block unless a condition is true.
unless (condition) {
# ...
}
or:
unless (condition) {
# ...
} else {
# ...
}
The until Loop
#!/usr/bin/perl
$num=0;
until ($num == 10){
print "$num ";
$num++;
}
print "\nOut of the loop.\n";
The until modifier repeatedly executes the second expression as long as the first expression is false.
#Format: Expression2 until Expression1;
$x=1;
print $x++,"\n" until $x == 5;
The until statement
#With until, the block is repeated so long as the condition remains false.
#You can read the command as "loop until the condition is true."
#You can reverse the while test with the until statement:
#until (condition) {
# # ...
#}
#!/usr/bin/perl -w
$i = 0;
until ($i >= 10) {
print "Iteration $i.\n";
$i++;
}
The while command
#The while command loops while a condition is true.
#So long as the condition remains true, all of the commands inside the block execute again and again.
#while (condition) {
# # ...
#}
#!/usr/bin/perl -w
$i = 0;
while ($i < 10) {
print "Iteration $i.\n";
$i++;
}
The while Loop
#!/usr/bin/perl
$num=0;
while ($num < 10){
print "$num ";
$num++;
}
print "\nOut of the loop.\n";
The while, until, and do Statements
#!/usr/local/bin/perl
$count = 0;
while ($count < 4){
print "Inside the while loop the count is $count\n";
$count++;
}
print "now $count\n\n";
until ($count > 7){
$count++;
print "Inside the until loop the count is $count\n";
}
print "now $count\n\n";
do {
print "The do statement is always executed at least once.The count is $count\n";
$count++;
} until ($count >7);
do {
print "The do statement is always executed at least once. The count is $count\n\n";
$count++;
} while ($count < 4);
do {
print "The do statement can act as a loop. Here the count is $count\n";
$count++;
} while ($count < 14);
Two ranges
#!c:/perl/bin
@mynumbers = (1..20, 25..40);
for($loopcount=0; $loopcount<40; $loopcount++)
{
print "@mynumbers[$loopcount] \n";
}
unless statement
#!/usr/local/bin/perl -w
while (<STDIN>)
{
chop;
print "I have found what I'm looking for: <$_>\n" unless $_ ne "Tom";
}
unless statement in while
while (<>) {
print "Too small!\n" unless $_ > 100;
}
unless statement with else
$variable = 6;
unless ($variable == 5) {
print "No, it's not five.\n";
} else {
print "Yes, it's five.\n";
}
unless statement with elsif
$variable = 2;
unless ($variable != 1) {
print "Yes, it's one.\n";
} elsif ($variable == 2) {
print "Yes, it's two.\n";
} elsif ($variable == 3) {
print "Yes, it's three.\n";
} elsif ($variable == 4) {
print "Yes, it's four.\n";
} elsif ($variable == 5) {
print "Yes, it's five.\n";
} else {
print "Sorry, can't match it!\n";
}
until statement
#!/usr/bin/perl -w
use strict;
my $countdown = 5;
until ($countdown <= 0) {
print "Counting down: $countdown\n";
$countdown--;
}
until with continue
$loop_index = 1;
until ($loop_index > 10) {
print "Hello!\n";
} continue {
$loop_index++;
}
until with diamond operator
until (($line = <>) eq 'q\n') {
print $line;
}
until with integer
$loop_index = 1;
until ($loop_index > 10) {
print "Hello!\n";
$loop_index++;
}
Use a label
$Pattern = "perl";
$File = "myfile";
open (FILE,$File) || die "Can't open $File, $!\n";
FileLoop:
while(<FILE>) {
if (/$Pattern/o) {
print "$File: $_";
last FileLoop;
}
}
close(FILE);
Use an elsif statement to check if a different condition is true
$lang = <STDIN>;
chomp($lang);
if ( $lang eq "perl" ) {
print "Congratulations, you choose perl!\n";
} elsif ( $lang eq "Tcl" ) {
print "Tcl is great, too.\n";
} else {
print "Well, use $lang if you feel ";
}
Use foreach to loop through hash with keys function
$hash{sandwich} = ham;
$hash{drink} = 'AA';
foreach $key (keys %hash) {
print $hash{$key} . "\n";
}
Use for loop to output all elements in an array
@array = ("one", "two", "three");
for ($loop_index = 0; $loop_index <= $#array; $loop_index++)
{
print $array[$loop_index] . " ";
}
Use for loop to output the element one by one in an array
@array = ("one", "two", "three");
for ($loop_index = 0; $loop_index <= $#array; $loop_index++) {
print $array[$loop_index] . " ";
}
Use if statement to check the integer value
$variable = 5;
if ($variable == 5) {
print "Yes, it's five.\n";
}
Use range operator with for statement
$factorial = 1;
for (1 .. 6) {
$factorial *= $_;
}
print "6! = $factorial\n";
Uses the for statement to read four input lines and write three of them.
#!/usr/local/bin/perl
for ($line = <STDIN>, $count = 1; $count <= 3; $line = <STDIN>, $count++) {
print ($line);
}
Use until to read user input
#!/usr/bin/perl
print "Are you o.k.? ";
chomp($answer=<STDIN>);
until ($answer eq "yes"){
sleep(1);
print "Are you o.k. yet? ";
chomp($answer=<STDIN>);
}
Use while loop to read console input
while ($_ = <>) {
print $_;
}
while (<>) {
print;
}
Use while loop to read console input and replace
while (<>) {
for (split) {
s/m/y/g;
print;
}
}
while ($_ = <>) {
for $_ (split / /, $_) {
$_ =~ s/m/y/g;
print $_;
}
}
Using a label.
#!/usr/local/bin/perl
$total = 0;
$firstcounter = 0;
DONE: while ($firstcounter < 10) {
$secondcounter = 1;
while ($secondcounter <= 10) {
$total++;
if ($firstcounter == 4 && $secondcounter == 7) {
last DONE;
}
$secondcounter++;
}
$firstcounter++;
}
print ("$total\n");
Using a label without a loop and the redo statement
#!//usr/bin/perl
ATTEMPT: {
print "Yes/No? ";
chomp($answer = <STDIN>);
unless ($answer eq "yes"){
redo ATTEMPT ;
}
}
Using array length in foreach statement
#!/usr/bin/perl -w
use strict;
my @questions = qw(Java Python Perl C);
my @punchlines = ("A","B","C",'D');
foreach (0..$#questions) {
print " $questions[$_] ";
sleep 2;
print $punchlines[$_], "\n\n";
sleep 1;
}
Using block labels with next.
LOOP: for ( $number = 1; $number <= 10; ++$number ) {
next LOOP if ( $number % 2 == 0 );
print "$number ";# displays only odd numbers
}
Using block labels with next in nested looping structures.
OUTER: foreach $row ( 1 .. 10 ) {
INNER: foreach $column ( 1 .. 10 ) {
if ( $row < $column ) {
print "\n";
next OUTER;
}
print "$column";
}
}
Using both next and continue
while ($loop_index <= 10) {
print "Hello\n";
next if $loop_index > 5;
print "there\n";
} continue {
$loop_index++;
}
Using do .. until statement
#!/usr/bin/perl -w
use strict;
my $i = 1;
print "starting do...until\n";
do {
print " the value of \$i: $i\n";
$i++;
} until ($i >= 6);
Using foreach loops with hashes.
@opinions = qw( A b c d e f g h jk r e r t r e e e e e ww );
foreach ( @opinions ) {
++$hash{ $_ };
}
print "Word\tFrequency\n";
print "----\t---------\n";
foreach ( sort keys( %hash ) ) {
print "$_\t", "*" x $hash{ $_ }, "\n";
}
Using foreach statement with hash
$hash{fruit} = orange;
$hash{sandwich} = club;
$hash{drink} = lemonade;
foreach $key (keys %hash) {
print $hash{$key} . "\n";
}
Using foreach statement with print
print "Current number: $_.\n" foreach (1 .. 10);
Using foreach to iterate over an array.
@array = ( 1 .. 10 ); # create array containing 1-10
foreach $number ( @array ) { # for each element in @array
$number **= 2;# square the value
}
print "@array\n";
Using foreach to loop through an array without using the default value
#!/usr/bin/perl -w
use strict;
my $element;
foreach $element ('zero', 'one', 'two') {
print "the element is: $element\n";
}
Using foreach to loop through array variable
#!/usr/bin/perl -w
use strict;
my @array = qw(A B C D);
my $element;
foreach $element (@array) {
print $element, "\n";
}
Using for loop to sum the total
@a = (1, 2, 3, 4, 5, 6, 7, 8, 9);
$running_sum = 0;
for ($loop_index = 0; $loop_index <= $#a + 1; $loop_index++) {
$running_sum += $a[$loop_index];
}
print "Average value = " . $running_sum / ($#a + 1);
Using if statements with relational and equality operators
print "Please enter first integer: ";
$number1 = <STDIN>;
chomp $number1;
print "Please enter second integer: ";
$number2 = <STDIN>;
chomp $number2;
print "The integers satisfy these relationships: \n";
if ( $number1 == $number2 ) {
print "$number1 is equal to $number2.\n";
}
if ( $number1 != $number2 ) {
print "$number1 is not equal to $number2.\n";
}
if ( $number1 < $number2 ) {
print "$number1 is less than $number2.\n";
}
if ( $number1 > $number2 ) {
print "$number1 is greater than $number2.\n";
}
if ( $number1 <= $number2 ) {
print "$number1 is less than or equal to $number2.\n";
}
if ( $number1 >= $number2 ) {
print "$number1 is greater than or equal to $number2.\n";
}
Using if statement to check if a variable has been defined
$variable1 = 5;
undef $variable1;
if (defined $variable1) {
print "\$variable1 is defined.\n";
} else {
print "\$variable1 is not defined.\n";
}
Using if statement to check if a variable is zero
if ($bottom) {
$result = $top / $bottom;
}
else {
$ result = 0;
}
Using if statement to check the number entered from keyboard
#!/usr/bin/perl -w
use strict;
my $target = 12;
print "Guess my number!\n";
print "Enter your guess: ";
my $guess = <STDIN>;
if ($target == $guess) {
print "That's it! You guessed correctly!\n";
exit;
}
if ($guess > $target) {
print "Your number is more than my number\n";
exit;
}
if ($guess < $target){
print "Your number is less than my number\n";
exit;
}
Using my inside for statement
$factorial = 1;
for (my $loop_index = 1; $loop_index <= 6; $loop_index++) {
$factorial *= $loop_index;
}
Using nested for loop to assign value to two dimensional array
for $outerloop (0..4) {
for $innerloop (0..4) {
$array[$outerloop][$innerloop] = 1;
}
}
print $array[0][0];
Using nested for loop to output the elements in a two-dimensional array
@array = (
["A", "F"],
["B", "E", "G"],
["C", "D"],
);
for $outer (0..$#array) {
for $inner (0..$#{$array[$outer]}) {
print $array[$outer][$inner], " ";
}
print "\n";
}
Using predefined variable $_ in foreach loop
#!/usr/bin/perl -w
use strict;
my @array = (10, 20, 30, 40);
print "Before: @array\n";
foreach (@array) {
$_ *= 2;
}
print "After: @array\n";
Using the do/until repetition structure
$counter = 10;
do
{
print "$counter ";
} until ( --$counter == 0 );
print "\n";
Using the do/while repetition structure
$counter = 1;
do
{
print "$counter ";
} while ( ++$counter <= 10 );
print "\n";
Using the equality-comparison operator to compare two numbers entered at the keyboard.
#!/usr/local/bin/perl
print ("Enter a number:\n");
$number1 = <STDIN>;
chop ($number1);
print ("Enter another number:\n");
$number2 = <STDIN>;
chop ($number2);
if ($number1 == $number2) {
print ("The two numbers are equal.\n");
}
print ("This is the last line of the program.\n");
Using the goto statement.
#!/usr/local/bin/perl
NEXTLINE: $line = <STDIN>;
if ($line ne "") {
print ($line);
goto NEXTLINE;
}
Using the if elsif statement to check the number entered from keyboard
#!/usr/bin/perl -w
use strict;
my $target = 12;
print "Guess my number!\n";
print "Enter your guess: ";
my $guess = <STDIN>;
if ($target == $guess) {
print "That's it! You guessed correctly!\n";
} elsif ($guess > $target) {
print "Your number is more than my number\n";
} elsif ($guess < $target) {
print "Your number is less than my number\n";
}
Using the last statement in a foreach structure.
foreach ( 1 .. 10 ) {
if ( $_ == 5 ) {
$number = $_; # store current value before loop ends
last; # jump to end of foreach structure
}
print "$_ ";
}
print "\n\nUsed 'last' to terminate loop at $number.\n";
Using the next statement in a foreach structure.
foreach ( 1 .. 10 ) {
if ( $_ == 5 ) {
$skipped = $_; # store skipped value
next; # skip remaining code in loop only if $_ is 5
}
print "$_ ";
}
print "\n\nUsed 'next' to skip the value $skipped.\n";
Using the redo statement in a while structure.
$number = 1;
while ( $number <= 5 ) {
if ( $number <= 10 ) {
print "$number ";
++$number;
redo; # Continue loop without testing ( $number <= 5 )
}
}
print "\nStopped when \$number became $number.\n";
Using .. to construct array
print ("a" .. "z");
Using unless with regular expression
while (<>) {
chomp;
unless (/^q/i) {
print;
} else {
exit;
}
}
Using until with print statement
print "Please enter more text (q to quit).\n" until (<> eq "q\n");
Using variable defined outside in foreach loop
#!/usr/bin/perl -w
use strict;
my @array = (1, 3, 5, 7, 9);
my $i = "Hello there";
foreach $i (@array) {
print "This element: $i\n";
}
print "All done: $i\n";
Using while and for statement to check if you had typed in four letter words
while (<>) {
for (split) {
if (/^\w{4}$/) {
print "You shouldn't use four letter words.\n";
}
}
}
Using While loop the output the elements in an array
#!/usr/bin/perl -w
use strict;
my @names = qw(A B C D);
print "processing using a while loop:\n";
my $i = 0;
while ($i <= $#names) {
print " Hello $names[$i]!\n";
$i++;
}
Using while loop to calculate the number of lines in a file
$number_lines = 0;
open(FILEHANDLE, "file.txt") or die "Can not open file.txt";
while (<FILEHANDLE>) {
++$number_lines;
}
close FILEHANDLE;
print "The number of lines in file.txt = $number_lines.";
Using while loop with each
#!/usr/bin/perl -w
use strict;
my %where = (
G => "A",
L => "B",
I => "C",
S => "D"
);
my($k, $v);
while (($k, $v) = each %where) {
print "$k lives in $v\n";
}
Using while statement to check the entered value from keyboard
#!/usr/bin/perl -w
use strict;
while (<STDIN>) {
print "You entered: ";
print;
}
Using while statement to read from keyboard
while ($temp = <STDIN>) {
print $temp;
}
while and until loop
#!C:/perl/bin
$loopcounter = 1;
while ($loopcounter < 10)
{
print "loop count = $loopcounter ";
$loopcounter++
}
$loopcounter = 1;
print "\n\nThe Until Loop:\n";
until ($loopcounter > 10)
{
print "loop count = $loopcounter ";
$loopcounter++
}
while data section
while (<DATA>) {
print;
}
__DATA__
Here
is
the
text!
while (<DATA>) {
print;
}
__END__
Here
is
the
text!
While loop and counter
#!/usr/bin/perl
$count=10;
while ($count > 0) {
print "$count...\n";
$count = $count -1;
}
While loop counter
#!c:\perl\bin
print "\n\nHere is the pre-increment example: \n";
$count = 0;
while ($count < 5)
{
print "The value of \$count is " . ++$count . "\n";
}
print "\n\nHere is the post-increment example: \n";
$count = 0;
while ($count < 5)
{
print "The value of \$count is " . $count++ . "\n";
}
While loop, foreach loop, and block and redo
#!/usr/bin/perl
use warnings;
use strict;
my $n = 0;
print "With a while loop:\n";
while (++$n < 4) {
print "Hello $n \n";
}
print "With a foreach loop:\n";
foreach my $n (1..3) {
print "Hello $n \n";
}
print "With a bare block and redo: \n";
$n = 1; {
print "Hello $n \n";
last if (++$n > 3);
redo;
}
While statement and scalar control value
#!/usr/bin/perl -w
use strict;
my $countdown = 5;
while ($countdown > 0) {
print "Counting down: $countdown\n";
$countdown--;
}
while statement to read input
#!/bin/perl
while(<>){
($name, $phone)=split(/:/);
unless($name eq "barbara"){
$record="$name\t$phone";
print "$record";
}
}
print "\n$name has moved from this district.\n";
while/until Loop
#while ( conditional expression ) {
# code block A
#}
$count=0; # Initial value
while ($count < 10 ){ # Test
print $n;
$count++; # Increment value
}
You can use a for loop to loop for a specific number of times.
#for (initialization; expression; continue) {
# # ...
#}
#!/usr/bin/perl -w
for ($i = 0; $i < 10; $i++) {
print "Iteration $i.\n";
}