LevSelector.com |
Perl examples tutorial - under construction but still useful
This is a compilation of examples borrowed from several tutorials or
self-made. Arranged into chapters.
After you read them, copy/paste and run them - you will be able to
program in Perl on an average beginner level.
- Chapter 1, 2: Numeric and String Literals
- Chapter 3: Variables
- Chapter 4: Operators
- Chapter 5: Functions
- Chapter 6: Statements
- Chapter 7: Statements
- Chapter 8: References
- Chapter 9: Using Files
- Chapter 10: Regular Expressions
- Chapter 11: Creating Reports
- Chapter 12: Using Special Variables
-- Chapter 1,2 -- | home - top of the page - |
# --------------------------------------------------
print("My name is Yon Yonson,\n"); #
this is a comment
print("I live in Wisconsin,\n",
"I work in a lumbermill there.\n");
print("
I live in NY,
I work in GS there.
");
# decimal, octal, hexadecimal nubmers
print 123, ' ', 043, ' ', 0x23, "\n";
# float numbers
print 100.5, ' ', 54.534, ' ', 3.4E-5, "\n";
# quotes - single and double. Note using '\' to include special
# characters into the string:
print 'WasWaldo can\'t hit the broad side of a barn.', "\n";
print 'Morganna said, "WasWaldo can\'t hit anything."', "\n";
print "WasWaldo the Illusionist\n";
print "Morganna said, \"WasWaldo can't hit anything.\"", "\n";
# using embeded line-breaks:
print 'Bill of Goods
Bread: $34 .45
Fruit: $45.00
======
$79.45', "\n";
# ----- There are many Escape Sequences - to insert special characters
into strings, capitalize, etc.:
print "\uwas\uwaldo is \x33\x34 years old.\n";
print "The kettle was \Uhot\E!\n";
print "\nYet another example:\n";
print "Bill of Goods\n
Bread:\t\$34.45\nFruit:\t\$45.00\n\t======\n\t\$79.45\n";
print "Back-Quoted Strings are used to run external commands and collect
their output\n";
$allfiles = `dir *.pl`;
print "$allfiles\n";
print "===== hit 'Enter' to continue";
<>; # waiting for user to enter the line
# note: you can use qx() notation instead of back quotes, for
example:
print "------------------------------\n";
$allfiles = qx(dir *.pl);
print "$allfiles\n";
# --------------------------------------------------
# ----- arrays:
@arr1 = (); # empty array
@arr1 = ("This", "is", 'an', "array", 'of', "strings");
@arr2 = qw(This is an array of strings); # qw puts quotes and commas
for you
for (@arr2) { print "$_\n" }
print "Here is an empty array:" . () . "<-- Nothing there!\n";
print (12, 014, 0x0c, 34.34, 23.3E-3), "\n";
print ("This", "is", 'an', "array", 'of', "strings"), "\n";
print ("This", 30, "is", 'a', "mixed array", 'of', 0x08, "items", "\n");
print (1..15), "\n";
print (1, 2, 7..10, 14, 15, "\n");
print ("A", "B", "F".."H", "Y", "Z", "\n\n");
# ----- putting to lists into one:
@arr1 = qw( a b c d e ); @arr2 = qw( f g h i j);
@arr3 = (@arr1, @arr2);
print "@arr3 \n";
# ----- array returns its length in scalar context:
$length1 = @arr1; $length3 = @arr3;
print "\$length1 = $length1, \$length3 = $length3\n";
print "\n";
-- Chapter 3 -- Variables | home - top of the page - |
# --------------------------------------------------
print "\$ - scalars , \@ - arrays, \% - hashes\n";
$numberOfRooms = 23;
$bookTitle = "Perl by Example";
$numberOfRooms = $numberOfRooms + 5; # 23 +
5 = 28
$numberOfRooms += $numberOfRooms + 5; # 28
+ 5 = 33
@emptyArray = ();
@numberArray = (12, 014, 0x0c, 34.34, 23.3E-3);
@stringArray = ("This", "is", 'an', "array", 'of', "strings");
@mixedArray = ("This", 30, "is", 'a', "mixed array", 'of', 0x08, "items");
print "Here is an empty array:" . @emptyArray . "<- Nothing there!\n";
print @numberArray; print "\n";
print @stringArray; print "\n";
print @mixedArray; print "\n";
print "======== press 'Enter' to continue:";<>;
@smallArrayOne = (5..10);
@smallArrayTwo = (1..5);
@largeArray = (@smallArrayOne, @smallArrayTwo);
print @largeArray, "\n";
print "======== press 'Enter' to continue:";<>;
print "\narray indexing:\n";
@array = (1..5); # indexes 0..4, values 1..5
print @array, "\n";
print $array[0], "\n";
print $array[1], "\n";
print $array[2], "\n";
print $array[3], "\n";
print $array[4], "\n";
print $array[-1], "\n"; # last element = $array[4]
print $array[-2], "\n"; # = $array[3]
print $array[-3], "\n"; # = $array[2]
print $array[-4], "\n"; # = $array[1]
print $array[-5], "\n"; # = $array[0]
print "======== press 'Enter' to continue:";<>;
$index = 2;
print $array[$index], "\n";
print "\nnumber of elements:\n";
$numberOfElements = @array;
print "$numberOfElements\n";
print "======== press 'Enter' to continue:";<>;
print "\nGrab a slice of an Array:\n";
@array = ("One", "Two", "Three", "Four");
($first, $third) = @array[0, 2];
@arr = (0,2);
($first, $third) = @array[@arr]; # same thing
print("\$first=$first \$third=$third\n");
print "======== press 'Enter' to continue:";<>;
print "\nswap values of 2 variables:\n";
$aa = 'mama'; $bb='papa';
($aa, $bb) = ($bb, $aa);
print "$aa $bb\n";
# swap array elements
@array[0, 3] = @array[3, 0];
print("\@array=@array\n");
print "======== press 'Enter' to continue:";<>;
print "\nhashes (key-value pairs) - also called assotiative arrays:\n";
%hh = ("Jack A.", "Dec 2",
"Joe B.", "June 2");
$hh{"Jennifer S."} = "Mar 20";
print "Joe's birthday is: " . $hh{"Joe B."} . "\n";
print "Jennifer's birthday is: " . $hh{"Jennifer S."} . "\n";
print "======== press 'Enter' to continue:";<>;
print "\nprinting arrays - see the difference:\n";
print @array, "\n";
print scalar(@array), "\n";
print "@array\n"; # by default separates by spaces
$" = ",";
print "@array\n"; # no separates by commas
-- 4 -- Operators | home - top of the page - |
Chapter 4 - operators
# -----------------------------------------------
Operator Description
op1 + op2 Addition
op1 - op2 Subtraction
op1 * op2 Multiplication
op1 ** op2 Exponentiation
op1 / op2 Division
op1 % op2 Modulus
Example:
$aa = 4; print $aa ** 3, "\n"; # 64
# -----------------------------------------------
for($i=0;$i<=100;$i++) {
if($i % 10 == 0) {
print "$i ";
}
}
# 0 10 20 30 40 50 60 70 80 90 100
# -----------------------------------------------
++ and -- : pre - act before using operand in expression
after - act after using operand in expression
For example:
$aa = 5; $bb = $aa++; # now $bb == 5, $aa == 6;
$aa = 5; $bb = ++$aa; # now $bb == 6, $aa == 6;
# -----------------------------------------------
$aa = 5;
$aa = $aa + 3; # inconvenient - has to write $aa two times
$aa += 3; # shorter way - means
"increase by 3"
Other similar operators:
+=
-=
*=
/=
%=
**=
.= concatenate strings together:
$aa= "We are "; $aa .= "friends";
NOTE: similar you can use = with other operators described later:
var x= op1; # repetition
var <<= op1; # bit shifting
var >>= op1; # bit shifting
var &= op1; # bitwize AND
var |= op1; # bitwize OR
var ||= op1; # logical OR
var ^= op1; # logical XOR
# -----------------------------------------------
Check if something is true or false
if ($aa) { print "TRUE\n"; } else { print "FALSE\n" };
Three types of false values:
$aa = 0; # number zero
$aa = ""; # empty string
$aa = undef; # undefined value
Everything else is considered to be true
# -----------------------------------------------
Comparing equality:
== number values are the same
!= numbers are different
eq string values are the same
ne string values are different
$str1 = "1";
$str2 = "01";
if ($str1 eq $str2) { print "equal strings,"; } else { print "different
strings,"; }
if ($str1 == $str2) { print " equal numbers\n"; } else { print " different
numbers\n"; }
# different strings, equal numbers
# -----------------------------------------------
Comparing:
numbers: < , <= , > , >=
strings: lt, le , gt, ge # strings are compared by
their ascii order
# -----------------------------------------------
3-way comparing:
( op1 <=> op2 ) # this operator returns:
# 1 if op1 is greater than op2,
# 0 if op1 equals op2,
# -1 if op1 is less than op2.
( op1 cmp op2 ) # similar thing for strings
# -----------------------------------------------
Logical operators:
op1 && op2 - Performs a logical AND of the two operands.
NOTE: runs op2 only if op1 is "true"
returns result of the last operation
op1 || op2 - Performs a logical OR of the two operands.
NOTE: performs op2 only if op1 is "false"
returns result of the last operation
!op1 - Performs a logical NOT of the operand.
$aa = "mama";
$bb = "papa";
$cc = $aa && $bb;
print "$cc\n"; # papa
# -----------------------------------------------
low-priority version of logical operators:
and or not
if ($aa == 9 || $aa == 10) { print("Error!") }
if ($aa == 9 or $aa == 10) { print("Error!") }
# -----------------------------------------------
Bitwize operators:
1 00000001
2 00000010
3 00000011
4 00000100
etc.
op1 & op2 bitwize AND : (2 & 3) == 2
op1 | op2 bitwize OR : (2 & 3) == 3
op1 ^ op2 bitwize XOR (exclusive OR) : (2 ^ 3) ==
1
~op1 bitwize NOT (COMPLEMENT):
~63 = 4294967232
63 11111111 11111111 11111111 00111111
~63 11111111 11111111 11111111 11000000
op1 << op2 SHIFT bits LEFT (effectively multiplies by 2)
op1 >> op2 SHIFT bits RIGHT (effectively divides by 2 for positive
numbers)
print "\n", 8 << 3; # 64
print "\n", 8 >> 1; # 4
# -----------------------------------------------
Terniary operator: __ ? __ : __
Example1: getting one of 2 values
$max = ( $aa >= $bb ) $aa : $bb;
Example2: assigning to one of 2 values
$a1=1;$a2=2;$a3=3;
($a3 == 0 ? $a1 : $a2) = 4;
print "$a1 $a2 $a3\n"; # 1 4 3
# -----------------------------------------------
Range operator: ( .. )
@a = (1..10); # $a[0] == 1, $a[1] == 2, ..., $a[9] = 10
Examples of usage:
@arr = ("AAA", 1..5, "A".."D", "ZZZ");
@arr = ("aa" .. "af");
# -----------------------------------------------
The String Operators (. and x) - concatenation and repition.
$aa = "AA";
$bb = "BB";
$cc = $aa . $bb; # "AABB";
$separator = "-" x 20 . "\n";
print $separator; # --------------------
NOTE: you can use repetition operator to repeat array elements as well:
@arr = ('a') x 5;
print "@arr\n"; # a a a a a
Excercise:
@arr = ('A'..'G');
$aa = @arr x 2;
print("@arr\n"); # A B C D E F G
print("$aa\n"); # 77
# -----------------------------------------------
Assigning using array slices:
Example1:
@arr = (0..10);
@arr[4, 7] = ("AA","BB");
print("@arr\n"); # 0 1 2 3 AA 5 6 BB 8 9 10
Example2:
@arr1 = (0..10);
@arr2 = ("A".."Z");
@arr1[1..3] = @arr2[23..25];
print "@arr1\n"; # 0 X Y Z 4 5 6 7 8 9 10
# -----------------------------------------------
@arr = ("Tom Jones", "123 Harley Lane", "Birmingham", "AR");
($name, $street, $town, $state) = @arr;
print("$name, $street, $town, $state\n");
# -----------------------------------------------
Operator precedence:
$a1 = -2 ** 4;
$a2 = -(2 ** 4);
$a3 = (-2) ** 4;
print "$a1 $a2 $a3\n"; # -16 -16
16
# -----------------------------------------------
Questions to repeat the main topics of the chapter:
What are three arithmetic operators?
What does the x operator do?
What does it mean to pre-decrement a variable?
What is the value of 1 ^ 1?
What is the value of 1 << 3?
What is the ternary operator used for?
Can the x operator be used with arrays?
What is the precedence level of the range operator?
What is the value of 2 % 5 + 10?
What is the value of 65 >> 1?
What is the spaceship operator used for?
If an array were defined with ("fy".."gb"), what would its elements
be?
-- 5 -- Functions | home - top of the page - |
# functions = subroutins.
# Parameters passed as aliases into one array - @_.
# ----------------------------
sub s1 {
print "Hello, sub\n";
}
s1(); # calling this sub
# ----------------------------
sub s2 {
my ($a1, $a2) = @_;
print "$a $b\n";
}
s2("mama", 123);
# ----------------------------
sub s3 {
my $number = @_; # number of elements
print "number of parameters = $number : ";
for (@_) { print "$_ "; }
print "\n";
}
s3(1,2,3,"mama",'papa', 'crocodil');
s3(1, 2, 3, 4, 5, 6);
s3(1..3);
s3("A".."Z");
# ----------------------------
sub s4 {
my $x1=shift;
my $x2=shift;
return $x2 >= $x1 ? $x2 : $x1;
}
$max = s4(4,5);
# ----------------------------
sub s5 {
@_[0] +=1;
print "in sub: $_[0]\n";
}
$aa=1;
s5($aa);
print "after sub: $aa\n";
# ----------------------------
sub s6 {
my $x = shift;
$x++;
print "in sub: $x\n";
}
$aa=1;
s6($aa);
print "$aa\n";
# ----------------------------
sub s7 {
for (@_) { $_++ }
}
@arr = (1, 2, 3);
s7(@arr);
print "@arr\n";
# ----------------------------
sub areaOfCircle {
$radius = $_[0];
return(3.1415 * ($radius ** 2));
}
print areaOfCircle(5),"\n";
# ----------------------------
# you can call functions from other functions.
# You can even call function from itself recursively
$i=0;
sub p { print "$i "; p(++$i) if $i<100; }
p(); print "\n";
sub factorial {
my $x = shift;
$x= int($x);
if ($x<1) {
print "number should be a positive integer, exiting..";
exit(1);
}
return $x * factorial($x-1) if $x >=2;
return $x;
}
print factorial(5),"\n";
# ----------------------------
# local variables:
# local - temporarily make/substitute a global variable
# used
to temporary change values of special variables
# like
$/, $|, etc.
#
# my - create a true local variable
# which
is not visible outside the body of the sub
# ----------------------------
# some standard string functions:
# chomp(STRING) OR chomp(ARRAY)
# Uses the value of the $/ special variable to remove
endings from STRING
# or each element of ARRAY. The line ending is only
removed if it matches
# the current value of $/.
# chop(STRING) OR chop(ARRAY) Removes the last character from
a string or
# the last character from every element in an array.
The last character
# chopped is returned.
# chr(NUMBER) Returns the character represented by NUMBER in the
ASCII table.
# For instaNCe, chr(65) returns the letter A.
# crypt(STRING1, STRING2) ENCrypts STRING1.
# Unfortunately, Perl does not provide a decrypt
fuNCtion.
# index(STRING, SUBSTRING, POSITION) Returns the position of the
first
# occurreNCe of SUBSTRING in STRING at or after POSITION.
# If you don't specify POSITION, the search starts
at the beginning of STRING.
# join(STRING, ARRAY) Returns a string that consists of all of
the elements
# of ARRAY joined together by STRING.
# For instaNCe, join(">>", ("AA", "BB", "cc")) returns
"AA>>BB>>cc".
# lc(STRING) Returns a string with every letter of STRING in lowercase.
# For instaNCe, lc("ABCD") returns "abcd".
# lcfirst(STRING) Returns a string with the first letter of STRING
in lowercase.
# For instaNCe, lcfirst("ABCD") returns "aBCD".
# length(STRING) Returns the length of STRING.
# rindex(STRING, SUBSTRING, POSITION) Returns the position of
the last
# occurreNCe of SUBSTRING in STRING at or after POSITION.
# If you don't specify POSITION, the search starts
at the end of STRING.
# split(PATTERN, STRING, LIMIT) Breaks up a string based on some
delimiter.
# In an array context, it returns a list of the things
that were found.
# In a scalar context, it returns the number of things
found.
# substr(STRING, OFFSET, LENGTH) Returns a portion of STRING
as determined
# by the OFFSET and LENGTH parameters.
# If LENGTH is not specified, then everything from
OFFSET to the end
# of STRING is returned. A negative OFFSET can be
used to start from
# the right side of STRING.
# NOTE: also can be used to change a substring inside
the string:
# for example:
$str = "my mother is living with me";
print "$str\n";
substr($str, 3, 6) = "dad";
print "$str\n";
# uc(STRING) Returns a string with every letter of STRING in uppercase.
# For instaNCe, uc("abcd") returns "ABCD".
# Ucfirst(STRING) Returns a string with the first letter of STRING
# in uppercase. For instaNCe, ucfirst("abcd")
# -------------------------------------------
$pathName = "C:\\WINDOWS\\TEMP\\somefile.txt";
$position = rindex($pathName, "\\") + 1;
$fileName = substr($pathName, $position);
print("$fileName\n");
# -------------------------------------------
# Some functions often used with arrays and hashes:
# -------------------------------------------
$aa = undef;
print "NOT DEFINED\n" if not defined
$aa;
$aa = "";
print "DEFINED\n" if defined $aa;
# -------------------------------------------
%hh = ( k1 => 'v1', k2 => v2);
$kk = 'k3';
print "key '$kk' does not exist\n" if not exists
$hh{$kk};
$kk = 'k2';
delete $hh{$kk} if exists
$hh{$kk};
print "key '$kk' does not exist\n" if not exists
$hh{$kk};
# -------------------------------------------
# 2 ways to go through the elements of a hash
while (my ($kk,$vv) = each %hh)
{
do something with $kk and $vv
}
for my $key (keys %hh) {
print $hh{$key},"\n";
}
for (sort keys
%hh) {
print $hh{$_},"\n";
}
# -------------------------------------------
# 5 functions to add/remove elements of the array:
# push, pop, shift, unshift, splice
push @arr, $var; # add
one element to the end of the array - and assign its value to be $var
push @arr, (1,2,3); # add
3 elements
push @arr, @arr2, $var1, $var2;
# add many elements
$var = pop @arr; # remove
last element from the array and return it. Array gets shorter by 1.
$var = shift @arr; # same
as pop - but takes element from the beginning of the array
unshift @arr, $var; # same as push, but adds elements to the beginning of the array.
splice(@arr, $ofset, $length, @arr2);
# Replaces elements of @arr (starting at $ofset, number - $length)
# with elements of @arr2 (number elements in it may differ $length).
# It returns a list holding any elements that were removed.
# Note: special variable $[ may change the base array
subscript when determining the OFFSET value.
# -------------------------------------------
# make a string from the array of words using join( ):
# split string into an array of words using split():
@arr = qw(word1 word2 word3 word4);
print "@arr\n";
$string = join (":", @arr);
print "$string\n";
@arr2 = split (/:/, $string);
print "@arr2\n";
# -------------------------------------------
# use undef() to undefine variable, array or hash
$var = "";
@arr = (1,2,3);
%hh = (1=>2,3=>4);
print "defined \$var\n" if defined $var;
print "defined \@arr\n" if defined @arr;
print "defined \%hh\n" if defined %hh;
undef $var;
undef @arr;
undef %hh;
print "NOT defined \$var\n" if not defined $var;
print "NOT defined \@arr\n" if not defined @arr;
print "NOT defined \%hh\n" if not defined %hh;
# -------------------------------------------
$length = scalar @arr;
# forces to dot he same as $length = @arr;
# that is - evaluate array in a scalar context
# which returns the length (number of elements) of the
array
# -------------------------------------------
@arr = (1,2,3,4,'mama');
@revarr = reverse @arr; # reverse the order
of array elements
print "@revarr\n";
$revstr = reverse @arr; # concatenates all elements in
a string and reverses the string
print scalar reverse @arr; # amam4321
print "\n";
# -------------------------------------------
@sorted = sort @arr;
@sorted = sort { $a <=> $b } $arr;
# -------------------------------------------
# map and grep
map { some code with $_ } @arr;
@result = map { some code with $_ } @arr; # result elements
are calculated for each element of @arr;
@filtered = grep { some code with $_ } @arr; # filtered
are those for which code returns true;
# -------------------------------------------
pack(format, @arr); # creates a binary structure from @arr using
format
unpack(format, @arr); # the opposite of pack().
# -------------------------------------------
using q(), qq(), qw(), qx()
-- 6 -- | home - top of the page - |
-- 7 -- | home - top of the page - |
-- 8 -- | home - top of the page - |
-- 9 -- | home - top of the page - |
-- 10 -- | home - top of the page - |