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 Basic Program
@a1 = $v1 && 1 .. 10;
$v1 = 0;
@a1 = $v1 && 1 .. 10;
print join (" ", @a1);
A case-conversion program.
#!/usr/local/bin/perl
print ("Enter a line of input:\n");
$inputline = <STDIN>;
print ("uppercase: \U$inputline\E\n");
print ("lowercase: \L$inputline\E\n");
print ("as a sentence: \L\u$inputline\E\n");
Add 3 to $var; same as $var=$var+3
#!/usr/bin/perl
$var=0; # Assign 0 to var
$var += 3; # Add 3 to $var; same as $var=$var+3
print "\$var += 3 is $var \n";
Adding 10 to an undefined variable
$undefAdd = 10 + $undefNumber;
print "Adding 10 to an undefined variable: $undefAdd\n";
print "Printing an undefined variable: $undefVariable(end)\n";
Adding a number and a string
$string = "Top 10";
$number = 10.0;
print "Number is 10.0 and string is 'Top 10'\n\n";
$add = $number + $string;
print "Adding a number and a string: $add\n";
After incrementing
#!/usr/bin/perl -w
$a = 4;
$b = 10;
print "Our variables are ", $a, " and ", $b, "\n";
$b = $a++;
print "After incrementing, we have ", $a, " and ", $b, "\n";
After pre-decrement
#!/usr/bin/perl -w
$a = 4;
$b = 10;
print "Our variables are ", $a, " and ", $b, "\n";
$a = --$b + 4;
print "Finally, we have ", $a, " and ", $b, "\n";
After pre-increment: ++$a * 2
#!/usr/bin/perl -w
$a = 4;
$b = 10;
print "Our variables are ", $a, " and ", $b, "\n";
$b = ++$a * 2;
print "Now, we have ", $a, " and ", $b, "\n";
Aliases and Values
#!/usr/bin/perl
use warnings;
use strict;
my @array = (1..10);
foreach (@array) {
$_++;
}
print "Array is now: @array\n";
Alternative names for Perl system variables.
Variable Alternative name(s)
$_ $ ARG
$0 $PROGRAM_NAME
$< $REAL_USER_ID or $UID
$> $EFFECTIVE_USER_ID or $EUID
$( $REAL_GROUP_ID or $GID
$) $EFFECTIVE_GROUP_ID or $EGID
$] $PERL_VERSION
$/ $INPUT_RECORD_SEPARATOR or $RS
$\ $OUTPUT_RECORD_SEPARATOR or $ORS
$, $OUTPUT_FIELD_SEPARATOR or $OFS
$" $LIST_SEPARATOR
$# $OFMT
$@ $EVAL_ERROR
$? $CHILD_ERROR
$! $OS_ERROR or $ERRNO
$. $INPUT_LINE_NUMBER or $NR
$* $MULTILINE_MATCHING
$[ none (deprecated in Perl 5)
$; $SUBSCRIPT_SEPARATOR or $SUBSEP
$: $FORMAT_LINE_BREAK_CHARACTERS
$$ $PROCESS_ID or $PID
$^A $ACCUMULATOR
$^D $DEBUGGING
$^F $SYSTEM_FD_MAX
$^I $INPLACE_EDIT
$^L $FORMAT_FORMFEED
$^P $PERLDB
$^T $BASETIME
$^W $WARNING
$^X $EXECUTABLE_NAME
$& $MATCH
$' $PREMATCH
$' $POSTMATCH
$+ $LAST_PAREN_MATCH
$~ $FORMAT_NAME
$= $FORMAT_LINES_PER_PAGE
$- $FORMAT_LINES_LEFT
$^ $FORMAT_TOP_NAME
$| $OUTPUT_AUTOFLUSH
$% $FORMAT_PAGE_NUMBER
A more expanded version for showing how to use the $_
#!/usr/bin/perl -w
#
# This script prints out all
# files listed on the command line.
#
while (<ARGV>) {
print $_;
}
&&, ||, and !
#!/usr/bin/perl
use warnings;
print"Test one: ", 6 > 3 && 3 > 4, "\n";
print "Test two: ", 6 > 3 and 3 > 4, "\n";
An example of exponentiation
#!/usr/bin/perl
use warnings;
print 2**4, " ", 3**5, " ", -2**4, "\n";
An example of the -a option.
#!/usr/local/bin/perl
# This program is called with the -a and -n options.
while ($F[0] =~ /[^\d.]/) {
shift (@F);
next if (!defined($F[0]));
}
print ("$F[0] $F[1]\n");
Any line starting with a number sign (#) indicates a comment.
print "Wow.\n"; #This is a comment.
A package is a separate name space for variables to reside in.
package Nothing;
sub doNothing
{
print "This package does nothing!\n";
}
1;
A program that changes the value of $/.
#!/usr/local/bin/perl
$/ = ":";
$line = <STDIN>;
print ("$line\n");
A program that sorts input lines in reverse order.
#!/usr/local/bin/perl
@input = <STDIN>;
@input = reverse (sort (@input));
print (@input);
A program that uses AUTOLOAD.
#!/usr/local/bin/perl
¬here("hi", 46);
AUTOLOAD {
print("subroutine $AUTOLOAD not found\n");
print("arguments passed: @_\n");
}
A program that uses the -0 option.
#!/usr/local/bin/perl -0040
while ($line = <>) {
$line =~ s/\n//g;
next if ($line eq "");
print ("$line\n");
}
A program that uses the $" (dollar and quotation) variable.
#!/usr/local/bin/perl
$" = "::";
@array = ("This", "is", "a", "list");
print ("@array\n");
A program that uses the $\(dollar and slash) variable.
#!/usr/local/bin/perl
$\ = "\n";
print ("Here is one line.");
print ("Here is another line.");
A program that uses the $(dollar), variable.
#!/usr/local/bin/perl
$a = "hello";
$b = "there";
$, = " ";
$\ = "\n";
print ($a, $b);
A program that uses the -l option.
#!/usr/local/bin/perl -l014
print ("Hello!");
print ("This is a very simple test program!");
A program that uses the pre-increment operation.
#!/usr/local/bin/perl
$value = 0;
while (++$value <= 5) {
print("value is now $value\n");
}
print("all done\n");
ARGV and the Null Filehandle
while( <ARGV> ) {print ;}
print "The value of \$ARGV[0] is $ARGV[0].\n";
ARGV in Perl represents the command-line arguments.
# <ARGV> represents opening each file that is listed by name on the command line.
# @ARGV is a Perl array that contains each of the command-line arguments as a separate array element.
#!/usr/bin/perl -w
# Lists command-line arguments.
# Get first argument.
$arg = shift(@ARGV);
# Loop while there is an argument.
while (defined $arg) {
print "$arg\n";
# Get next argument.
$arg = shift(@ARGV);
}
Arithmetic Operators in action
printf "%d\n", 4 * 5 / 2;
printf "%d\n", 5 ** 3;
printf "%d\n", 5 + 4 - 2 * 10;
printf "%d\n", (5 + 4 - 2 ) * 10;
printf "%d\n", 11 % 2;
A scalar is a variable that holds a single value, a single string, or a number.
# The name of the scalar is preceded by a "$" sign. Scalar context means that one value is being used.
$first_name = "M";
$last_name = "Q";
$salary = 125000.00;
print $first_name, $last_name, $salary;
A scalar variable can reference a string value or a numeric value.
# Perl has three contexts: string context, numeric context, and miscellaneous context.
$name="Tom";
$age=3;
$height=4.5;
A simple Perl program that reads and writes a line of input.
#!/usr/local/bin/perl
$inputline = <STDIN>;
print( $inputline );
A simple Perl program with comments.
#!/usr/local/bin/perl
# this program reads a line of input, and writes the line back out
$inputline = <STDIN>; # read a line of input
print( $inputline ); # write the line out
A simple version of the cat command using $_.
#!/usr/local/bin/perl
print while (<>);
Assign a number to a single variable
#!/usr/bin/perl
print "Content-Type: text/html \n\n";
# The code below makes it easy to change numbers output by the script.
$cars_on_lot = 100;
print "<p>Welcome to <b>AUTO!</b></p>";
print "<p>Which one of our $cars_on_lot cars is
right for you?</p>\n";
Assign elements in @_ to scalar
sub addem
{
($value1, $value2) = @_;
return $value1 + $value2;
}
print "2 + 2 = " . addem(2, 2) . "\n";
Assigning Input to an Array
# Assigning input to an array
print "Tell me everything about yourself.\n ";
@all = <STDIN>;
print "@all";
print "The number of elements in the array are: ",$#all + 1, ".\n";
print "The first element of the array is: $all[0]";
Assignment Operators
Operator Example Meaning
= $var = 5; Assign 5 to $var
+= $var += 3; Add
-= $var -= 2; Subtract
.= $str.="ing"; Concatenate ing to $str
*= $var *= 2; Multiply $var by 2
/= $var /= 2; Divide $var by 2
**= $var **= 2; Square $var
%= $var %= 2; Divide $var by 2
x= $str x= 2; Repeat value of $str 2 times
<<= $var <<= 1; Left-shift bits in $var one position
>>= $var>>= 2; Right-shift bits in $var two positions
&= $var &= 1; One is bitwise-ANDed to $var
|= $var |= 2; Two is bitwise-ORed to $var
^= $var ^= 2; Two is bitwise-exclusive ORed to $var
Assignment Statements
variable=expression;
$salary=50000; # Scalar assignment
@months=('Mar', 'Apr', 'May'); # Array assignment
%states= ( # Hash assignment
'CA' => 'California',
'NM' => 'New Mexico',
);
Assign new value to string variable
#!/usr/bin/perl -w
$name = "A";
print "My name is ", $name, "\n";
print "It's still ", $name, "\n";
$name = "B";
print "Well, actually, now it's ", $name, "\n";
$name = "C";
print "No, really, now it's ", $name, "\n";
Assign new value to the integer scalar variable
#!/usr/bin/perl -w
$a = 6 * 9;
print "Six nines are ", $a, "\n";
$a = $a + 3;
print "Plus three is ", $a, "\n";
$a = $a / 3;
print "All over three is ", $a, "\n";
$a = $a + 1;
print "Add one is ", $a, "\n";
Assign string array to @ARGV by using qw
#!/usr/bin/perl -w
use strict;
@ARGV = qw/file1.txt file2.txt file3.txt/;
while (<>) {
print;
}
Assign text to a single variable
#!/usr/bin/perl
print "Content-Type: text/html \n\n";
# The code below makes it easy to change text output.
$company_name = "AUTO";
$cars_on_lot = 100;
$deal_of_day = "Ford";
print "<p>Welcome to $company_name!</p>\n";
print "<p>Which one of our $cars_on_lot cars is right for you?</p>\n";
print "<p>Today we have a GREAT deal on a $deal_of_day.</p>\n";
Assign value to @_
sub addem
{
($value1, $value2) = @_;
$value1 + $value2;
}
@_ = (2, 2);
$value = &addem;
print "2 + 2 = $value\n";
Assign value to a variable without declaration
$x = 100;
$y = 200;
$warning = "Do you smell smoke?";
Assign value to four variables
#!C:\perl\bin
$age = $myage = $herage = $hisage = 25;
print "\$age = $age\n\n";
print "\$myage = $myage\n\n";
print "\$herage = $herage\n\n";
print "\$hisage = $hisage\n\n";
Autoincrement and Autodecrement Operators and Assignment
#!/usr/bin/perl
$x=5; $y=0;
$y=++$x; # Add 1 to $x first; then assign to $y
print "Pre-increment:\n";
print "y is $y\n";
print "x is $x\n";
$x=5;
$y=0;
print "Post-increment:\n";
$y=$x++; # Assign value in $x to $y; then add 1 to $x
print "y is $y\n";
print "x is $x\n";
Auto local variable
#!/usr/bin/perl
use warnings;
use strict;
my $var = 42;
my $last;
print "Before: $var \n";
foreach $var (1..5) {
print "Inside: $var \n"; # print "Inside: 1", "Inside: 2" ...
$last = $var;
}
print "After: $var \n"; # prints '42'
print "Last: $last \n";
Basic arithmetic operators.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
Basic Math Compound Assignment Statements
#! /usr/local/bin/perl
$a = 5;
print "\$a equals $a before the operation.\n ";
$a += 4.2;
print "The result of \$a += 4.2 is $a \n";
print "\$a equals $a before the operation.\n ";
$a -= 4.2;
print "The result of \$a -= 4.2 is $a \n";
print "\$a equals $a before the operation.\n ";
$a *= 4.2;
print "The result of \$a *= 4.2 is $a \n";
print "\$a equals $a before the operation.\n ";
$a /= 6;
print "The result of \$a /= 6 is $a \n";
print "\$a equals $a before the operation.\n ";
$a %= 6;
print "The result of \$a %= 6 is $a \n";
Basic Numeric Operations
#! /usr/local/bin/perl
$a = 4.2 + 3;
print "The result of 4.2 + 3 is $a \n";
$a = 4.2 - 3;
print "The result of 4.2 - 3 is $a \n";
$a = 4.2 * 3;
print "The result of 4.2 * 3 is $a \n";
$a = 26 / 8;
print "The result of 26 / 8 is $a \n";
$a = 26 % 8;
print "The result of 26 % 8 is $a \n";
Begin and End block
#!/usr/bin/perl
use warnings;
use strict;
END {
print "Exiting... \n";
}
print "Running! \n";
fun();
sub fun {
print "Inside fun \n";
}
BEGIN {
print "Compiling... \n";
}
Bitwise And Operators in action
print 5 & 4,"\n"; # 101 & 100
print 5 & 0,"\n"; # 101 & 000
print 4 & 0,"\n"; # 100 & 000
print 0 & 4,"\n"; # 000 & 100
print "=" x 10,"\n"; # print 10 equal signs
Bitwise exclusive or Operators in action
print 5 ^ 4,"\n"; # 101 ^ 100
print 5 ^ 0,"\n"; # 101 ^ 000
print 4 ^ 0,"\n"; # 100 ^ 000
print 0 ^ 4,"\n"; # 000 ^ 100
Bitwise Logical Operators
Operator Example Meaning
& $x & $y Bitwise and
| $x | $y Bitwise or
^ $x ^ $y Bitwise exclusive or
<< $x << 1 Bitwise left shift, integer multiply by two
>> $x >> 1 Bitwise right shift, integer divide by two
Bitwise operator
#!/usr/bin/perl
use warnings;
use strict;
my $a = 3;
my $b = 6;
my $r;
printf "$a = %03b \n", $a;
printf "$b = %03b \n", $b;
$r = $a & $b; printf "$a & $b = %03b = %d\n", $r, $r;
$r = $a | $b; printf "$a | $b = %03b = %d\n", $r, $r;
$r = $a ^ $b; printf "$a ^ $b = %03b = %d\n", $r, $r;
$r = ~$a; printf "~$a = %03b = %d\n", $r, $r;
Bitwise Or Operators in action
print 1 | 4,"\n"; # 001 & 100
print 5 | 0,"\n"; # 101 | 000
print 4 | 0,"\n"; # 100 | 000
print 0 | 4,"\n"; # 000 | 100
print "=" x 10,"\n"; # print 10 equal signs
Block main
#!/usr/bin/perl
use strict;
use warnings;
my $global_variable = "All the World can see Me";
use constant MY_GLOBAL_CONSTANT => "Global Constant";
MAIN: {
my $main_variable = "Not visible outside main block";
print_variables ($main_variable);
}
sub print_variables {
print $global_variable, "\n", MY_GLOBAL_CONSTANT, "\n";
print $_[0], "\n"; # passed from main block, ok now
}
Blocks
#!/usr/bin/perl
use warnings;
use strict;
$SIG{__DIE__} = sub {
print "DIE?\n";
};
print "It's alive!\n";
die "death!\n";
BEGIN {
print "BEGIN\n";
}
END {
print "END\n";
}
INIT {
print "INIT\n"
}
CHECK {
print "CHECK\n"
}
Block variable scope
#!/usr/bin/perl
use warnings;
use strict;
my $text = "This is the child";
{
my $text = "This is block scoped";
print "$text \n";
}
print "$text \n";
Boolean and: &&
print "Please enter positive numbers up to 100\n";
while (<>) {
chomp;
if ($_ > 0 && $_ < 100) {
print "Thank you - let's have another!\n";
} else {
print "Please enter positive numbers up to 100\n";
}
}
Boolean Combination Operators
Operator Means
&& Logical AND
|| Logical OR
! Logical NOT
Boolean operator: ||
print "Please enter numbers from 5 to 10\n";
while (<>) {
chop;
if ($_ < 5 || $_ > 10) {
print "Please enter numbers from 5 to 10\n";
} else {
print "Thank you - let's have another!\n";
}
}
Build the ARGV array with qw function
#!/usr/bin/perl -w
use strict;
@ARGV = qw(file1.dat file2.dat file3.dat);
while (<>) {
print "text read: $_";
}
Built-in Perl Arithmetic Functions
atan2(Y,X) Returns the arctangent of Y/X.
cos(EXPR)
cos EXPR Returns the cosine of EXPR in radians. If EXPR is omitted, takes cosine of $_.
exp(EXPR)
exp EXPR Returns e to the power of EXPR. If EXPR is omitted, gives exp($_).
int(EXPR)
int EXPR Returns the integer portion of EXPR. If EXPR is omitted, uses $_.
log(EXPR)
log EXPR Returns logarithm (base e) of EXPR. If EXPR is omitted, returns log of $_.
rand(EXPR)
rand EXPR
rand Returns a random fractional number between 0 and the value of EXPR.
If EXPR is omitted, returns a value between 0 and 1.
sin(EXPR)
sin EXPR Returns the sine of EXPR in radians. If EXPR is omitted, returns sine of $_.
sqrt(EXPR)
sqrt EXPR Return the square root of EXPR. If EXPR is omitted, returns square root of $_.
srand(EXPR)
srand EXPR Sets the random number seed for the rand operator. If EXPR is omitted, does srand(time).
Built-in variables: $_
$_ allows you to write minimalist Perl scripts:
#!/usr/bin/perl -w
# This script prints out all
# files listed on the command line.
#
while (<>) { # From <ARGV>
print; # Prints $_
}
Call-by-Reference and the @_ Array
#Passing arguments
$first="Tom";
$last="Kary";
&greeting ( $first, $last );
sub greeting{
print "@_", "\n";
print "Welcome, $_[0] $_[1]!\n";
}
Capturing fatal errors
#!usr/bin/perl
use warnings;
use strict;
my $line = "25 / 0";
eval ( $line );
print "There is an error:\n" if $@;
print $@;
Catching the sigINT signal
#!/usr/bin/perl
use strict;
my $interruptions = 0;
$SIG{INT} = \&handle_interruptions;
while ($interruptions < 3) {
print "waiting.\n";
sleep(5);
}
sub handle_interruptions {
$interruptions++;
warn "interrupted ${interruptions}x.\n";
}
Check a specific bit
$flag = 2030136;
if ($flag & 1 << 3) {
print "The third bit is set.";
}
else {
print "The third bit is not set.";
}
cmp with or
@name = qw(A B C D E);
@category = qw(a b c d e);
@subcategory = qw(1 2 3 4 5);
@indices = sort {$category[$a] cmp $subcategory[$b] or $category[$a] cmp $subcategory[$b]} (0 .. 4);
foreach $index (@indices) {
print "$category[$index]/$subcategory[$index]: $name[$index]\n";
}
Code the $_ specifically
while($_ = <STDIN>) {
print $_;
}
Commenting Your Code
#In Perl, you preface comments with a # .
#Perl will ignore all the text on a line after the # symbol.
# This is the comment.
print "Hello\tfrom\tPerl.\n";
Comments are plain text that allow you to insert documentation in your Perl script.
Perl does not understand the C language comments /* and */ or C++ comments //.
# This is a comment
print "hello"; # And this is a comment
Compare integer value
$numvar1 = 5;
$numvar2 = 6;
if ($numvar1 == 5)
{
print "The first number is equal to 5 \n";
}
if ($numvar2 != 5)
{
print "The second number is not equal to 5! \n";
}
Compare string value
#!c:\perl\bin
$string1="B";
$string2="E";
if($string1 == $string2)
{
print "Those two names are the same! \n"
}
Compare the first four decimal places
sub eqfloat4 {
return sprintf("%.4f", shift) eq sprintf("%.4f", shift);
}
if (eqfloat4 1.23455, 1.23456) {
print "Numbers are equal to four decimal places.";
}
Compare value entered with number with underscore
$savings = 0;
while ($savings < 1_000_000) {
print "Enter the amount: ";
$savings += <>;
}
Comparing Numbers for Equality
#!/usr/bin/perl
use warnings;
print"Is two equal to four? ", 2 == 4, "\n";
print "OK, then, is six equal to six? ", 6 == 6, "\n";
Comparing Numbers for Inequality
#!/usr/bin/perl
use warnings;
print"Five is more than six? ", 5 > 6, "\n";
print "Seven is less than sixteen? ", 7 < 16, "\n";
print "Two is equal to two? ", 2 == 2, "\n";
print "One is more than one? ", 1 > 1, "\n";
print "Six is not equal to seven? ", 6 != 7, "\n";
Comparison Operators listing
#! /usr/local/bin/perl
$booleanResult = (4 == 4);
print ' 4 == 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (3 == 4);
print ' 3 == 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (4 != 4);
print ' 4 != 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (3 != 4);
print ' 3 != 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (4 < 4);
print ' 4 < 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (3 < 4);
print ' 3 < 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (5 < 4);
print ' 5 < 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (5 > 4);
print ' 5 > 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (3 > 4);
print ' 3 > 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (4 > 4);
print ' 4 > 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (4 >= 4);
print ' 4 >= 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (3 >= 4);
print ' 3 >= 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (5 >= 4);
print ' 5 >= 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (4 <= 4);
print ' 4 <= 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (5 <= 4);
print ' 5 <= 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (3 <= 4);
print ' 3 <= 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (4 <=> 4);
print ' 4 <=> 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (3 <=> 4);
print ' 3 <=> 4; Results in ';
print "booleanResult = $booleanResult\n";
$booleanResult = (5 <=> 4);
print ' 5 <=> 4; Results in ';
print "booleanResult = $booleanResult\n";
Operator Example Description
== $a == 4; Equal to
!= $a != 4; Not equal to
< $a < 4; Less than
> $a > 4 ; Greater than
>= $a >= 4; Greater than or equal to
<= $a <= 4 ; Less than or equal to
<=> $a <=> 4 ; Compare
Complex Assignment
$degrees = 2;
($degrees += 100) *= 700;
print $degrees;
$degrees = 2;
$degrees += 100;
$degrees *= 700;
print $degrees;
Compound Assignment Operators
Operator Example Meaning
+= $a += 3; Add
-= $a -= 3; Subtract
*= $a *= 3; Multiply
/= $a /= 3; Divide
**= $a **= 3; Raise the power
%= $a %= 3; Modulo
.= $a .= "String Value"; Append
x= $a x= 3; Multiply (replicate) the expression (string)
&= $a &= 3; Binary AND
|= $a |= 3; Binary OR
^= $a ^= 3; Exclusive OR
<<= $a <<= 3; Left shift
>>= $a >>= 3; Right shift
&&= $a &&= 1; Logical AND
||= $a ||= 0; Logical OR
Compound assignment operator with scalar variable
$x = 2;
$x += 2;
print $x;
$x -= 2;
print $x;
$x *= 5;
print $x;
Compound Boolean operator Or: ||=
$value = 0;
$default = 100;
$value ||= $default;
print $value;
Compound operator
#!/usr/bin/perl -w
$a = 6 * 9;
print "Six nines are ", $a, "\n";
$a += 3;
print "Plus three is ", $a, "\n";
$a /= 3;
print "All over three is ", $a, "\n";
$a += 1;
print "Add one is ", $a, "\n";
Concatenate two scalar variables with double quotes
$a = "Hello";
$b = "there";
$c = "$a $b\n";
print $c;
Conditional debug
#!/usr/bin/perl
use strict;
use warnings;
use subs qw(debug);
unless (defined &debug) {
if ($ENV{DEBUG_ENABLED}) {
*debug = sub { print STDERR "@_\n" };
} else {
*debug = sub { }; #stub
}
}
debug "In debug mode";
Conditional Operator: (condition) ? statement_if_true : statement_if_false;
$coin = int (rand(2 )) + 1; # Generate a random number between 1 and 2
print ( $coin == 1 ? "You tossed HEAD\n" : "You tossed TAIL\n" );
Conditional Operators and print statement
print "What was your grade? ";
$grade = <STDIN>;
print $grade > 60 ? "Passed.\n" : "Failed.\n";
Constant scalar
#!/usr/bin/perl
use warnings;
use strict;
use vars qw($constantstring);
*constantstring=\"immutable";
print $constantstring;
$constantstring='no!';
Contents of the symbol table for the main package.
#!/bin/perl
use strict "vars";
use warnings;
our ( @friends, @dogs, $key, $value );
my($name,$pal,$money);
$name="Tom";
@friends=qw(A B C );
@dogs = qw(a b c);
local $main::dude="Tom";
my $pal = "another name";
while(($key, $value) = each (%main::)){
print "$key:\t$value\n";
}
Convert to scalar
#!/usr/bin/perl
use warnings;
use strict;
my %hash = (one => 1, two => 2, three => 3, four => 4, five => 5);
if (%hash) {
print scalar(%hash); # produces '4/8'
}
Creates a global variable $myvar and prints out the global instance of the variable and the package-specific variable:
#!/usr/local/bin/perl -w
# Define a variable.
$myvar = "Hello";
# Print out the global variable.
print "Global : $myvar \n";
# Print out the package specific variable.
print "Specific: $main::myvar \n";
Creating a Scalar
#The syntax for creating a scalar is: $variableName = <value>
# in which value may be numeric (integer or float),
# string
# reference (scalar, array, hash, code, or package)
# or boolean (True or False)
$scalar1 = 'this is a scalar'; # simple scalar assigned 'this is string'
$print = 10.0; # simple scalar assigned 10 (rounding is done)
$print = '10.0'; # number that is also a string, assigned 10.0.
$scalar2 = "this is $print"; # interpolation, assigned 'this is 10.0'
$scalar3 = 'this is $print'; # non-interpolation, assigned 'this is $print'
$emptyString = ''; # empty string.
Curly Braces
curly braces {} shields any characters that may be appended to the variable.
$var="net";
print "${var}work\n";
$data is a scalar variable, while @data is an array
$data = "Here's the data.";
@data = (1, 2, 3);
print $data;
print @data;
Debug flag
#!/usr/bin/perl -s -w
use strict;
use vars '$debug';
use if $debug, 'File::Basename' => 'basename';
use if !$debug, autouse => 'File::Basename' => 'basename';
print "Before: ",join(",",keys %INC),"\n";
my $prog=basename($0);
print "After : ",join(",",keys %INC),"\n";
Declare scalar variable to store the integer value
#!/usr/bin/perl -w
$a = 6 * 9;
print "Six nines are ", $a, "\n";
$b = $a + 3;
print "Plus three is ", $b, "\n";
$c = $b / 3;
print "All over three is ", $c, "\n";
$d = $c + 1;
print "Add one is ", $d, "\n";
print "\nThose stages again: ", $a, " ", $b, " ", $c, " ", $d, "\n";
Declare three variables in one statement
$x = $y = $z = 1;
print join (", ", $x, $y, $z);
Default package is main
@town = qw(A C T);
$friend="Tom";
print "\$friend is $friend\n";
package boy;
$name="Mary";
print "In boy \$name is $name.\n";
$main::friend="Jack";
print "In boy \@town is @::town\n";
package main;
print "In main: \$name is $name\n";
print "In main: \$name is $boy::name\n";
print "In main: \$friend is $friend.\n";
Define variables with the same name in different package
#!/usr/bin/perl -w
$main::name = "Your Name Here";
$Tom::name = "Tom";
$Jack::name = "Jack";
print "\$name in package main is $name\n";
print "\$name in package Tom is $Tom::name\n";
print "\$name in package Jack is $Jack::name\n";
Demonstrates the difference between pre- and postincrement
$c = 5;
$d = 5;
print $c, " ";
print $c++, " ";
print $c, "\n";
print $d, " ";
print ++$d, " ";
print $d, "\n";
$(dollar), is the separator
@array = ("one", "two", "three");
$, = ",";
print "Here is the array: ", @array, ".\n";
Don't use == when you should use eq!
$x = "yes";
$y = "no";
print "\nIs yes equal to no? If so, say 1; if not say 'null'.\n";
print "The result is: ",$x == $y,"\n"; # Should be $x eq $y
do .. while with diamond operator
do {
print;
} while (<>);
Downloading and Installing Modules using Perl -MCPAM
perl -MCPAN -e "install module_name"
For example:
perl -MCPAN -e "install Business::UPS"
Downloading and Installing Windows Modules using ppm
PPM> install Tk
Install package 'Tk?' (y/N): y
Retrieving package 'Tk'...
Edit files using the -i option.
#!/usr/local/bin/perl -i
while ($line = <>) {
while ($line =~ s#\d+\s*[*+-/]\s*\d+(\s*[*+-/]\s*\d+)*#<x>#) {
eval ("\$result = $&;");
$line =~ s/<x>/$result/;
}
print ($line);
}
Ending modifiers
You can execute a simple Perl statement if a condition is true, by reversing the if statement syntax:
statement if condition;
This technique is called an ending modifier.
You can also do this for unless, while, and until, as shown in the following code:
statement unless condition;
statement while condition;
statement until condition;
eq, ne, lt, gt operators
#!perl
@fruits = qw( apple orange banana );
foreach $item ( @fruits )
{
if ( $item eq "banana" )
{
print "String '$item' matches string 'banana'\n";
}
if ( $item ne "banana" )
{
print "String '$item' does not match string 'banana'\n";
}
if ( $item lt "banana" )
{
print "String '$item' is less than string 'banana'\n";
}
if ( $item gt "banana" )
{
print "String '$item' is greater than string 'banana'\n";
}
}
Equality Operators and Numeric Values
Operator Example Meaning
== $num1 == $num2 $num1 is equal to $num2
!= $num1 != $num2 $num1 is not equal to $num2
<=> $num1 <=> $num2 $num1 is compared to $num2 with a signed return;
1 if $num1 is greater than $num2,
0 if $num1 is equal to $num2, and
-1 if $num1 is less than $num2
Equality Operators and String Values
Operator Example Meaning
eq $str1 eq $str2 $str1 is equal to $str2
ne $str1 ne $str2 $str1 is not equal to $str2
cmp $str1 cmp $str2 $str1 is compared to $str2, with a signed return
Error message is stored in $!
#!/usr/bin/perl -w
use strict;
open(FH, '<', 'yourFileName.dat') or die $!;
print "goodopen.dat opened successfully\n";
close FH;
Examples of assignment operators.
Statement using Equivalent Perl assignment operator statement
$a = 1; assignment
$a -= 1; $a = $a - 1;
$a *= 2; $a = $a * 2;
$a /= 2; $a = $a / 2;
$a %= 2; $a = $a % 2;
$a **= 2; $a = $a ** 2;
$a &= 2; $a = $a & 2;
$a |= 2; $a = $a | 2;
$a ^= 2; $a = $a ^ 2;
Executing the Script
$ perl -c scriptname
Extracts information from the $] variable.
#!/usr/local/bin/perl
$] =~ /Revision: ([0-9.]+)/;
$revision = $1;
$] =~ /Patch level: ([0-9]+)/;
$patchlevel = $1;
print ("revision $revision, patch level $patchlevel\n");
File-searching program using $ARGV.
#!/usr/local/bin/perl
print ("Enter the search pattern:\n");
$string = <STDIN>;
chop ($string);
while ($line = <>) {
if ($line =~ /$string/) {
print ("$ARGV:$line");
}
}
Float power
print 144 ** .5;
print 81 ** .25;
print 2 * 4;
foreach (@_)
sub addone
{
foreach (@_) {
$_++;
}
return @_;
}
@a = (1, 2, 3);
@b = addone(@a);
print "@b";
foreach loop and $_
#!/usr/bin/perl
@colors=(red, green, blue, brown);
foreach (@colors) {
print "$_ ";
$_="YUCKY";
}
print "\n@colors\n";
Format text output with HTML tags
#!/usr/bin/perl
print "Content-Type: text/html \n\n";
print "<h1 align=center>\n";
print "Welcome to AUTO\n";
print "</h1>\n";
$_ for print function
#!C:\Perl\Bin\
$_ = "asdf! \n";
print;
Forward Reference
#!/usr/bin/perl
sub bye; # Forward reference
$name="Tom";
print "Hello $name.\n";
bye; # Call subroutine without the ampersand
sub bye{
print "Bye $name\n";
}
Get Computer Name key in the %ENV
print $ENV{'ComputerName'};
Get local time from $^T
$s = localtime($^T);
print $s;
Get reference to a scalar
#!/usr/bin/perl
use warnings;
use strict;
my $text = "This is a value";
my $ref1 = \$text;
my $ref2 = \$text;
print $ref1 == $ref2;
$$ref1 = 'New value';
print $$ref2;
Get the documentation of the built-in function
Replace stat with the name of the built-in function you are interested in.
perldoc f stat
Get the Power
#!/usr/bin/perl -w
print 2**4, " ", 3**5, " ", -2**4, "\n";
Getting information on modules
perldoc modulename
For example:
perldoc File::Copy
Getting Input in Perl Scripts
# Note the extra space after the question mark.
print "What is your favorite scripting language? ";
$lang = <STDIN>;
chomp($lang);
if ( $lang eq "perl" ) {
print "you chose perl!\n";
} else {
print "$lang ";
}
Guess My Number
#!/usr/bin/perl
use warnings;
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 bigger than my number\n";
exit;
}
if ($guess < $target){
print "Your number is less than my number\n";
exit;
}
@_ has runtime scope.
# Each subroutine has its own copy of @_,
#!/usr/bin/perl
use warnings;
use strict;
first(1,2,3);
sub first {
print "In first, arguments are @_\n";
second(4,5,6);
print "Back in first, arguments are @_\n";
}
sub second {
print "In second, arguments are @_\n";
}
If $_contains needle, the string is printed.
$_ = "a needle in a haystack";
print if /needle/;
If not equal
#!/usr/bin/perl -w
use strict;
print "please enter a number: ";
chomp(my $number = <STDIN>);
my $result = 0;
if ($number != 0) {
$result = 100 / $number;
}
print "the result is: $result\n";
If terminator is in backquotes, will execute OS commands
print "\nLet's execute some commands.\n";
print <<'END';
echo Today is
date
END
If there are no quotes, then Perl has to decide whether the value is a string or a numeric value.
#!/usr/local/bin/perl -w
$firstName=Tom;
$lastName="Jordan";
$age="3";
If the strings are not quoted, the filehandle STDOUT must be specified, or
the print function will treat the first word it encounters as a filehandle.
print Hello, world, "\n";
If variable defined
#!/usr/bin/perl -w
use strict;
my ($a, $b);
$b = 10;
if (defined $a) {
print "\$a has a value.\n";
}
if (defined $b) {
print "\$b has a value.\n";
}
Increment and Decrement Operations
#! /usr/local/bin/perl
$a=15;
$b = ++$a -15;
$c = $a++ - 15;
print "The increment operation occurs first on the left side\n";
print "$b = ++$a - 15 results in $b equal ";
print "$b\n";
print "The increment operation occurs after other operations when on the right side\n";
print "$c = $a- - 15 results in $c equal ";
print "$c\n";
Increment and Decrement Operators
Operator Example Description
+ $a = 3 + 4; Add
- $a = 34; Subtract
* $a = 3 * 4; Multiply
/ $a = 3 / 4; Divide
** $a = 2 ** 4; Raise the power
% $a = 36 % 8; Modulo the expression on the left of the operator by the expression on the right of the operator.
%INC values
#!/usr/bin/perl
use strict;
print "\%INC contains: \n";
foreach (keys %INC) {
print " $INC{$_}\n";
}
require File::Copy;
do '/home/perl/include.pl';
print "\n\%INC now contains: \n";
foreach (keys %INC) {
print " $INC{$_}\n";
}
Initializing scalars and printing their values
$num = 5;
$friend = "AA";
$money = 125.75;
$now = localtime(); # localtime() is a Perl function
$month = "Jan";
print "$num\n";
print "$friend\n";
print "I need \$$money.\n"; # Protecting our money
print qq/$friend gave me \$$money.\n/;
print qq/The time is $now\n/;
print "${month}uary.\n"; # Curly braces shield the variable
print "$month" . "uary.\n"; # Concatenate
In Perl, an assignment itself can serve as an lvalue.
chop ($input = 123);
print $input;
chop ($input = <>);
print $input;
Insert comments
#!/usr/bin/perl
print "Content-Type: text/html \n\n";
# This is a simple script with comments that explain what the code does.
# These comments do not affect the way the script works.
print "Welcome to AUTO!"; # You
# can even put comments on the same line as executable code.
Integer-comparison operators.
Operator Description
< Less than
> Greater than
== Equal to
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
<=> Comparison returning 1, 0, or -
Integer signal
sub sig_handler {
my $signal = shift;
die "I got signal $signal";
}
$SIG{INT} = \&sig_handler;
while(<>) {
print;
}
$\ is 'END_OF_OUTPUT'
$\ = "END_OF_OUTPUT";
print "Hello!";
$# is the default format
$pi = 3.1415926;
$# = '%.6g';
print "$pi\n";
$! is the error number
$! = 1;
print "$!\n";
print "Error number " , 0 + $! , " occurred.";
$~ is the format
format standardformat_top =
Employees
First Name Last Name ID Extension
--------------------------------------------
.
format standardformat =
@<<<<<<<<<<<<@<<<<<<<<<<<<@<<<<<<<<@<<<<
$firstname $lastname $ID $extension
.
$firstname = "A";
$lastname = "B";
$ID = 1234;
$extension = x456;
open FILEHANDLE, ">report.frm" or die "Can't open file";
select FILEHANDLE;
$~ = standardformat;
$^ = standardformat_top;
write;
close;
$^ is the format header
format standardformat_top =
Employees
First Name Last Name ID Extension
--------------------------------------------
.
format standardformat =
@<<<<<<<<<<<<@<<<<<<<<<<<<@<<<<<<<<@<<<<
$firstname $lastname $ID $extension
.
$firstname = "A";
$lastname = "B";
$ID = 1234;
$extension = x456;
open FILEHANDLE, ">report.frm" or die "Can't open file";
select FILEHANDLE;
$~ = standardformat;
$^ = standardformat_top;
write;
close;
$" is the separator
@array = (1, 2, 3);
$" = ',';
$text = "@array";
print $text;
Left shift
print 2 << 10;
Lexical variables
#!/usr/bin/perl
use warnings;
my $record = 4;
print "We're at record ", $record, "\n";
{
my $record;
$record = 7;
print "Inside the block, we're at record ", $record, "\n";
}
print "We're still at record ", $record, "\n";
Libraries and Modules
Library files have a .pl extenson;
modules have a .pm extension.
Path to Libraries
@INC array contains list of path to standard Perl libraries.
#To load an external file, use either require or use.
require("getopts.pl"); # Loads library file at run time
use CGI; # Loads CGI.pm module at compile time
Lines Remaining on the Page: $-
#!/usr/local/bin/perl
open (OUTFILE, ">outfile");
select ("OUTFILE");
write;
print STDOUT ("lines to go before write: $-\n");
write;
print STDOUT ("lines to go after write: $-\n");
format OUTFILE =
This is a test.
.
format OUTFILE_TOP =
This is a test.
.
List all command line argument
#!/usr/bin/perl -w
use strict;
print "[$_]\n" foreach @ARGV;
Local builtin var
#!/usr/bin/perl -w
use strict;
sub printwith {
my ($separator, @stuff)=@_;
local $, = $separator; # create temporary local $,
print @stuff,"\n";
}
printwith("... ","one","two","three");
Local element
#!/usr/bin/perl
our @array=(1,2,3);
{
local $array[1]=4;
print @array,"\n";
}
print @array,"\n",
Local to Block
Variable What It Does
$1.. $9 Remembered subpatterns
$& The string matched by the last pattern match
$' The string preceding what was matched in the last pattern match
$' The string that follows whatever was matched by the last pattern match
$+ The last pattern matched by the last search pattern
Local variables.
#!/usr/local/bin/perl
$total = 0;
while (1) {
$linetotal = &get_total;
last if ($linetotal eq "done");
print ("Total for this line: $linetotal\n");
$total += $linetotal;
}
print ("Total for all lines: $total\n");
sub get_total {
my ($total, $inputline, @subwords);
my ($index, $retval);
$total = 0;
$inputline = <STDIN>;
if ($inputline eq "") {
return ("done");
}
$inputline =~ s/^\s+|\s*\n$//g;
@subwords = split(/\s+/, $inputline);
$index = 0;
while ($subwords[$index] ne "") {
$total += $subwords[$index++];
}
$retval = $total;
}
Locate all numbers less than 6
@numbers = ( 1 .. 10 );
print "\@numbers: @numbers\n\n";
foreach ( @numbers ) {
push( @smallNumbers, $_ ) if $_ < 6;
}
print "Numbers less than 6:\n", "foreach: @smallNumbers\n";
Logical operators are defined
$a || $b # logical or: true if either is nonzero
$a && $b # logical and: true only if both are nonzero
! $a # logical not: true if $a is zero
Perl 5 also defines these logical operators:
$a or $b # another form of logical or
$a and $b # another form of logical and
not $a # another form of logical not
$a xor $b # logical xor: true if either $a or $b is nonzero, but not both
Logical Operators (Short-Circuit Operators)
Operator Alternative Form Example Meaning
&& and $x && $y If $x is true, evaluate $y and return $y
$x and $y If $x is false, evaluate $x and return $x
|| or $x || $y If $x is true, evaluate $x and return $x
$x or $y If $x is false, evaluate $y and return $y
xor $x xor $y True if $x or $y is true, but not both
! not !$x Not $x; true if $x is not true
not $x
Logical Word Operators
$num1=50;
$num2=100;
$num3=0;
print "\nOutput using the word operators.\n\n";
print "\n$num1 and $num2: ",($num1 and $num2), "\n";
print "\n$num1 or $num3: ", ($num1 or $num3), "\n";
print "\n$num1 xor $num3: ",($num1 xor $num3), "\n";
print "\nnot $num3: ", not $num3;
print "\n";
Loop block
#!/usr/bin/perl
use warnings;
use strict;
if (defined(my $line = <>)) {
{
last if $line =~/quit/;
print "You entered: $line";
$line = <>; redo;
}
}
print "Bye! \n";
Manipuate @_ and return @_
sub addone
{
foreach (@_) {
$_++;
}
return @_;
}
@a = (1, 2, 3);
@b = addone(@a);
print "@b";
Mannually change the $1 variable
$! = 1;
print "$!\n";
print "Error number " , 0 + $! , " occurred.";
Map using a block
open(FH, "datebook.master") or die;
@lines=<FH>;
@fields = map { split(":") } @lines;
foreach $field (@fields){
print $field,"\n";
}
Match: $&
$text = 'earlynowlate';
$text =~ /now/;
print "Prematch: \"$`\" Match: \"$&\" Postmatch: \"$'\"\n";
Merge scalar variable into the string for output
$text = "Hello";
print 'Perl says: $text!\n';
Minus power
print 2 ** -1
Mix the string the integer calculation in a print statement
#!/usr/bin/perl -w
print "21 from 25 is: ", 25 - 21, "\n";
Modifying a Variable
#!/usr/bin/perl
use warnings;
$name = "Tom";
print "My name is ", $name, "\n";
print "It's still ", $name, "\n";
$name = "bill";
print "Well, actually, it's ", $name, "\n";
$name = "Tom";
print "No, really, it's ", $name, "\n";
Module::get_scalar()
#!/usr/bin/perl
use warnings;
use strict;
use Symbol;
my $fqref = qualify_to_ref('scalar','My::Module');
$$fqref =\"Hello World\n";
print My::Module::get_scalar();
package My::Module;
our $scalar;
sub get_scalar {
return $scalar;
}
Modulus operator
#!/usr/bin/perl
$var=0;
$var %= 3; # Modulus
print "The remainder of \$var/3 is $var\n";
Naming Scalar Variables
The name you use for a scalar variable can contain letters, numbers, and underscores.
Such a name must start with the $ symbol.
A variable's name can be at least 255 characters long.
Scalar variable names are case sensitive-$variable1 is not the same as $Variable1.
no strict 'refs';
use strict 'refs';
$variable = 100;
{
no strict 'refs';
$variablename = "variable";
print $$variablename;
}
Not equals operator: ne
print "Please type the letter y\n";
while (<>) {
chop;
if ($_ ne 'y') {
print "Please type the letter y\n";
} else {
print "Do you always do what you're told?\n";
exit;
}
}
Numeric Literals
Example Description
12345 Integer
0b1101 Binary
0x456fff Hex
0777 Octal
23.45 Float
.234E+2 Scientific notation
Numeric operators
OPERATOR PURPOSE
+ Computes the additive value of the two operands.
Computes the difference between the two operands.
* Computes the multiplication of the two operands.
/ Computes the division between the two operands.
% Computes the modulus (remainder) of the two operands.
== Returns True if the two operands are equal, False otherwise.
!= Returns True if the two operands are not equal, False otherwise.
>= Greater than.
<= Less than.
>
<=> Returns -1 if the left operand is less than the right, +1 if is it greater than, and 0 (False) otherwise.
&& a logical AND operation.
|| a logical OR operation.
& Returns the value of the two operators bitwise ANDed.
| Returns the value of the two operators bitwise ORed.
~ Returns the value of the two operators bitwise XORed.
++ Increment operator. Increments the variable's value by 1.
-- Decrement operator. Decrements the variable's value by 1.
xx Computes the power of the left value to the power of the right value.
+= Adds the value of the right operand to the value of the left operand.
-= Subtracts the value of the right operand from the value of the left operand.
x= Multiplies the value of the left operand with the value of the right operand.
>> Shifts the left operand right by the number of bits specified by the right operand.
<< Shifts the left operand left by the number of bits specified by the right operand.
~ Performs a 1s complement of the operator. This is a unary operator.
Operating and Assigning at Once
#!/usr/bin/perl
use warnings;
$a = 6 * 9;
print "Six nines are ", $a, "\n";
$a += 3;
print "Plus three is ", $a, "\n";
$a /= 3;
print "All over three is ", $a, "\n";
$a += 1;
print "Add one is ", $a, "\n";
? operator
test ? execute_if_true : execute_if_false;
#!/usr/bin/perl -w
@ar = get_value();
print "Wanted array. Got back: @ar\n";
$v = get_value();
print "Wanted scalar. Got back: $v\n";
sub get_value {
my(@array) = (1, 2, 3);
my($val) = 55;
return wantarray ? @array : $val;
}
Operator associativity.
Operator Associativity
++, -- Not applicable
-, ~, ! Right-to-left
** Right-to-left
=~, !~ Left-to-right
*, /, %, x Left-to-right
+, -, . Left-to-right
<<, >> Left-to-right
<, <=, >, >=, lt, le, gt, ge Left-to-right
==, !=, <=>, eq, ne, cmp Left-to-right
& Left-to-right
|, ^ Left-to-right
&& Left-to-right
|| Left-to-right
.. Left-to-right
? and : Right-to-left
=, +=, -=, *=, Right-to-left
, Left-to-right
not Left-to-right
and Left-to-right
or, xor Left-to-right
Operator precedence.
Operator Operation Performed
++, -- Autoincrement and autodecrement
-, ~, ! Operators with one operand
** Exponentiation
=~, !~ Pattern-matching operators
*, /, %, x Multiplication, division, remainder, repetition
+, -, . Addition, subtraction, concatenation
<<, >> Shifting operators
-e, -r, etc. File-status operators
<, <=, >, >=, lt, le, gt,ge Inequality-comparison operators
==, !=, <=>, eq, ne, cmp Equality-comparison operators
& Bitwise AND
|, ^ Bitwise OR and XOR
&& Logical AND
|| Logical OR
.. List-range operator
? and : Conditional operator (together)
=, +=, -=, *=, Assignment operators and so on
, Comma operator
not Low-precedence logical NOT
and Low-precedence logical AND
or, xor Low-precedence logical OR and XOR
Operators demo: Arithmetic Operators
print "\nArithmetic Operators\n";
print ((3+2) * (5-3)/2);
Operators demo: Combined Assignment Operators
print "\nCombined Assignment Operators\n";
$a = 47;
$a += 3; # short for $a = $a + 3
$a++; # autoincrement
print $a; # Prints 51
Operators demo: Comparison Operators
print "\nComparison Operators\n";
print 5>=3 , "\n";
print 47==23 , "\n";
Operators demo: Logical Operators
print "\nLogical Operators\n";
$a > $b && $b < 100
$answer eq "yes" || $money == 200
Operators demo: String Operators
print "\nString Operators\n"; # Concatenation
print "\tTommy" . ' ' . "Savage";
or die $!
$filename = "file.dat";
open FILEHANDLE, ">$filename" or die $!;
or die $^E;
$filename = "file.dat";
open FILEHANDLE, ">$filename" or die $^E;
$^O stores the name of the operating system
print $^O;
Output the result of division with string
#!/usr/bin/perl -w
print "249 divided by 3 is ", 249 / 3, "\n";
Output the result of multiply with string
#!/usr/bin/perl -w
print "7 times 15 is ", 7 * 15, "\n";
Output two values in one print statement
print "Hello ", "there!\n";
Out value scope
#!/usr/bin/perl
use warnings;
use strict;
package MyPackage;
my $my_var = "my-var";
our $our_var = "our-var";
our $local_var = "global-var";
use vars qw($use_var);
$use_var = "use-var";
package AnotherPackage;
print "Outside, my_var is '$my_var' \n";
print "Outside, our_var is '$our_var' \n";
print "Outside, local_var is '$local_var' \n";
#-----
sub sub1 {
my $my_var = "my_in_sub1";
our $our_var = "our_in_sub1";
local $local_var = "local_in_sub1";
print "In sub1, my_var is '$my_var'\n";
print "In sub1, our_var is '$our_var'\n";
print "In sub1, local_var is '$local_var'\n";
sub2();
}
sub sub2 {
print "In sub2, my_var is '$my_var'\n";
print "In sub2, our_var is '$our_var'\n";
print "In sub2, local_var is '$local_var'\n";
}
#-----
sub1();
print "Again outside, my_var is '$my_var' \n"; # display 'my-var'
print "Again outside, our_var is '$our_var' \n"; # display 'our-var'
print "Again outside, local_var is '$local_var' \n"; # display 'global-var'
Package declarations and subroutine
$name="out";
$num=1;
package myPackage;
sub welcome {
print "Who is your pal? ";
chomp($name=<STDIN>);
print "Welcome $name!\n";
print "\$num is $num.\n";
print "Where is $main::name?\n\n";
}
package main;
&friend::welcome;
print "main package \$name is $name\n";
print "friend package, Bye ",$friend::name,"\n";
print "Bye $name\n\n";
package anotherPackage;
$name="AAA";
print "Hi $name.\n";
print "$::name and $friend::name\n";
Passing Arguments at the Command Line
# The @ARGV array holds command-line arguments.
# If the ARGV filehandle is used, the arguments are treated as files.
#
#$ perlscript filea fileb filec
print "@ARGV\n"; # lists arguments: filea fileb filec
while(<ARGV>){ # filehandle ARGV -- arguments treated as files
print; # Print each line of every file listed in @ARGV
}
Passing scalar variable to a subroutine by reference using $_
#!/usr/bin/perl -w
use strict;
my $var = 10;
print "before: $var\n";
change_var($var);
print "after: $var\n";
sub change_var {
print "in change_var() before: $_[0]\n";
++$_[0];
print "in change_var() after: $_[0]\n";
}
Perl 5 Built-In Variables
Variable English Name Description
$_ $ARG default input and pattern-searching space
$& $MATCH string matched by the last successful pattern match
$` $PREMATCH string preceding whatever was matched by the last successful pattern
$' $POSTMATCH string following whatever was matched by the last successful pattern
$+ $LAST_PAREN_MATCH last bracket matched by the last search pattern
$* $MULTILINE_MATCHING Perl 5 does multi-line matching within a string if it is 1(the default is 0)
$. $INPUT_LINE_NUMBER current input line number from the last file handle read
$/ $INPUT_RECORD_SEPARATOR The input record separator (newline by default)
$| $OUTPUT_AUTOFLUSH If it is nonzero, forces a flush after every write or print on the currently selected output device (the default is 0)
$, $OUTPUT_FIELD_SEPARATOR field separator for the print function
$\ $OUTPUT_RECORD_SEPARATOR record separator for the print function
$" $LIST_SEPARATOR list separator for the print function
$; $SUBSCRIPT_SEPARATOR subscript separator for multidimensional array emulation
$# $OFMT format for printed numbers
$% $FORMAT_PAGE_NUMBER page number for file handle output
$= $FORMAT_LINES_PER_PAGE page length for file handle output
$- $FORMAT_LINES_LEFT number of lines left on the page
$~ $FORMAT_NAME current format
$^ $FORMAT_TOP_NAME current top-of-page format
$: $FORMAT_LINE_BREAK_CHARACTERS characters after which a string may be separated to fill continuation fields
$^L $FORMAT_FORMFEED The value a format will output for each form feed
$^A $ACCUMULATOR write() accumulator for format() lines
$? $CHILD_ERROR status returned by the last pipe close, backtick (``) command, or system() operator
$! $ERRNO current numeric or string value of error number
$^E $EXTENDED_OS_ERROR Error information specific to the current operating system
$@ $EVAL_ERROR Perl syntax error message from the last eval() command
$$ $PROCESS_ID process number of the Perl running this script
$< $REAL_USER_ID uid of this process
$> $EFFECTIVE_USER_ID effective uid of this process
$( $REAL_GROUP_ID real gid of this process
$) $EFFECTIVE_GROUP_ID effective gid of this process
$0 $PROGRAM_NAME name of the file used to invoke the executing program
$[ index of the first element in an array and of the first character in a substring
$] $PERL_VERSION version and patch level of the Perl interpreter
$^D $DEBUGGING value of the debugging flags
$^F $SYSTEM_FD_MAX maximum system file descriptor
$^H set of syntax checks enabled by use strict and other pragmas
$^I $INPLACE_EDIT value of the in-place edit extension
$^M An emergency pool of allocated memory, used after an out-of-memory condition for printing error messages
$^O $OSNAME name of the operating system under which this copy of Perl was built, as determined during the configuration process
$^P $PERLDB internal variable for debugging support
$^R The result of evaluation of the last successful regular expression
$^S state of the interpreter
$^T $BASETIME The time at which the script began running, in seconds since the epoch
$^W $WARNING The current value of the warning switch, either true or false
$^X $EXECUTABLE_NAME Perl binary
$ARGV current file when reading from <>
@ARGV An array that contains the command-line arguments
@INC An array that contains the list of places to look for Perl scripts to be evaluated by the do EXPR, require, or use constructs (initially consists of the arguments to any -I command-line switches, followed by the default Perl library, followed by ``.'', which represents the current directory)
@_ Within a subroutine, an array that contains the parameters passed to that subroutine
%INC A hash that contains entries for each filename that has been included via do or require (the key is the filename you specified, and the value is the location of the file actually found)
%ENV A hash that contains your current environment (setting a value in %ENV changes the environment for child processes)
%SIG A hash used to set signal handlers for various signals
Perl can take its input from a file and send its output to a file using standard I/O redirection.
$ perl -ne 'print;' < yourTextFile
$ perl -ne 'print' emp.first > yourTextFile
Perl Flow Control Commands
Command Usage
goto label Jumps to named label.
Last Breaks out of the current innermost loop.
last label Breaks out of current loop at label.
Next Starts next iteration of loop.
next label Starts next iteration of loop, at label.
Redo Restarts the loop without re-evaluating condition.
redo label Restarts the loop label without re-evaluating condition.
Perl Flow Control in Brief
if (condition) { } elsif (condition) { } else { }
unless (condition) { } else { }
label: while (condition) { } continue { }
label: until (condition) { } continue { }
label: for (intialization; expression; continue) { }
label: foreach variable (list) { }
label: { } continue { }
do { } while condition;
do { } until condition;
do { }
Perl offers many types of operators
Assignment =, +=, -=, *= , %=, ^=, &=, |=, .=
Numeric equality ==, !=, <=>
String equality eq, ne, cmp
Relational numeric > >= < <=
Relational string gt, ge, lt, le
Range 5 .. 10 # range between 5 and 10, increment by 1
Logical &&, and, ||, or, XOR, xor, !
Autoincrement/decrement ++ --
File -r, -w, -x,-o, -e, -z, -s, -f, -d, -l, etc.
Bitwise ~ & | ^ << >>
String concatenation .
String repetition x
Arithmetic * / - + %
Pattern matching =~, !~
Perl's modules reside in the directories named in the @INC array, or subdirectories
#!/usr/bin/perl -w
# List directories in @INC.
foreach $dir (@INC) {
print "$dir\n";
}
Perl's operators for numeric comparisons
Numeric Comparison
Perl Usage
== Equal
!= Not equal
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
<=> Returns -1 if less than, 0 if equal and 1 if greater than
Perl's special arrays
ARRAY DESCRIPTION
@ARGV The command line arguments issued when the script was started.
@EXPORT The list of methods the package will export by default.
@EXPORT_OK The list of methods the package will export by request.
@INC The include path to search for libraries or Perl scripts.
@ISA The list of base classes of the package.
@_ The parameter array for subroutines.
%ENV This associative array contains your current environment.
%INC This associative array contains a record for each entry required using do or require.
%OVERLOAD Used to overload operators in a package.
%SIG This associative array contains signal handlers for various signals.
Perl's special variables
VARIABLE DEFAULT VALUE DESCRIPTION
$_ N/A The default input and pattern-searching space.
$digit N/A Contains the subpattern from a successful parentheses pattern match.
$& N/A The string from the last successful pattern match.
$ N/A The preceding string to the last successful pattern match.
$' N/A The string following the last successful pattern match.
$+ N/A The last bracket matched from the last search pattern.
$* 0 Controls internal string multiline pattern matching.
$. N/A The current input line number of last filehandle read.
$/ \n The input record separator.
$| 0 If set to nonzero, forces a flush of the currently selected stream after every write.
$, N/A The output field separator for the print command.
$" Space The separator that joins elements of arrays interpolated in strings.
$\ N/A The output record separator for the print command.
$; \034 The subscript separator for multidimensional array emulation.
$# N/A The output format for printed numbers.
$% N/A The page number of the currently selected output stream.
$= 60 The page length of the currently selected output stream.
$ N/A The number of lines left on the current page.
$ filehandle The name of the current top of page format for the currently selected output stream.
$: \n- The characters used to fill a continuation field.
$L \f The default form-feed character.
$? N/A The status value returned from the last system, pipe close, or back tick command.
$! N/A Contains the current value of errno.
$@ N/A The Perl syntax error from the last eval statement.
$$ N/A The process ID (PID) of the current running Perl script.
$< N/A The real user ID (UID) of the current running process.
$> N/A The effective UID of the current running process.
$( N/A The real group ID (GID) of the current running process.
$) N/A The effective GID of the current running process.
$0 N/A The name of the file of the Perl script.
$[ 0 The index of the first element of an array.
$] N/A The string printed out when Perl is run with the -v command line option.
$A N/A The accumulator for form line and write operations.
$D N/A The current value of the debugging flags.
$F 2 The maximum number of system file descriptors.
$I N/A Contains the current value of the in-place editing flag (-i).
$P N/A Internal debugging flag.
$T N/A The time in which the script began running.
$W N/A The current value of the warning switch.
$X N/A The name of the Perl binary that was executed.
$ARGV N/A The name of the current file when reading from <>.
Perl Statements
$result = 5 * 4 / 2;
print "Good-bye.\n";
print "Hello, to you!\n";
$now = localtime();
print "Today is $now.\n";
Perl statements end with a semicolon (;)
print "Wow.\n";
Perl supports integers (decimal, octal, hexadecimal), floating point numbers, scientific notation, Booleans, and null.
$year = 2006; # integer
$mode = 0775; # octal number in base 8
$product_price = 29.95; # floating point number in base 10
$favorite_color = 0x33CC99; # integer in base 16 (hexadecimal)
$distance_to_moon=3.844e+5; # floating point in scientific notation
$bits = 0b10110110; # binary number
Perl variables
A variable holds a value for you.
$lang indicates that lang is a variable.
The leading dollar sign, $, indicates that this variable is a scalar variable.
A scalar variable holds a single value.
Scalars in Perl hold a single number or a single string of characters.
Perl treats the entire string as a single value.
Arrays are another class of Perl variables.
Arrays store a list of numbers or text strings.
Place a # in the middle of a line, and Everything from the # to the end of the line is a comment.
print "Wow.\n"; # This is a comment in a line.
Post-increment operation.
#!/usr/local/bin/perl
$value = 0;
while ($value++ <= 5) {
print("value is now $value\n");
}
print("all done\n");
Postmatch $'
$text = 'earlynowlate';
$text =~ /now/;
print "Prematch: \"$`\" Match: \"$&\" Postmatch: \"$'\"\n";
Power with **
print 2 ** 16;
Precedence and Associativity
Operator Description Associativity
() [ ] { } Function call, array subscripts Left to right
** Exponentiation Right to left
! ~ \ + - Logical not, bitwise not, backslash, plus,minus Right to left
=~ !~ Match and not match Left to right
* / % x Multiply, divide, modulus, string repetition Left to right
+ -. Add, subtract, string concatenation Left to right
<< >> Bitwise left shift, right shift Left to right
-r -w -x -o etc. File test operators None
< <= > >= lt le gt ge Numeric and string: less than, greater than, etc. None
== != <=> eq ne cmp Numeric and string: equal to, not equal to, etc. None
& Bitwise and Left to right
| ^ Bitwise or, exclusive or (xor) Left to right
&& Logical and Left to right
|| Logical or Left to right
.. Range operator None
? : Ternary, conditional Right to left
= += -= *= /= %= Assignment Right to left
, => Left to right
not ! Right
and && Left to right
or xor ||, ^ Left to right
Precedence with word operators and short-circuit operators
$x=5;
$y=6;
$z=0;
$result=$x && $y && $z; # Precedence of = lower than &&
print "Result: $result\n";
$result2 = $x and $y and $z; # Precedence of = higher than and
print "Result: $result2\n";
$result3 = ( $x and $y and $z );
print "Result: $result3\n";
Pre-increment string value
$variable = 'AAA';
print ++$variable . "\n";
$variable = 'bbb';
print ++$variable . "\n";
$variable = 'zzz';
print ++$variable . "\n";
Prematch: $`
$text = 'earlynowlate';
$text =~ /now/;
print "Prematch: \"$`\" Match: \"$&\" Postmatch: \"$'\"\n";
print $_ >= 0 ? $_ : -$_
while (<>) {
print $_ >= 0 ? $_ : -$_
}
print 1, 2, 3, 4, sort 9, 8, 7, 6, 5;
print 1, 2, 3, 4, sort 9, 8, 7, 6, 5;
print 16 % 3;
print 16 % 3;
print 2048 >> 3;
print 2048 >> 3;
print 24 & 15;
print 24 & 15;
Print all command line argument
#!/usr/bin/perl -w
use strict;
print "contents of @ARGV:\n";
print "[$_]\n" foreach @ARGV;
print "\$0: $0\n";
print -e STDIN; #Does STDIN exist?
print -e STDIN; #Does STDIN exist?
printf Flag Modifiers
Conversion Definition
%- Left-justification modifier
%# Integers in octal format are displayed with a leading 0;
integers in hexadecimal form are displayed with a leading 0x
%+ integers are displayed with a numeric sign, + or -
%0 pad with zeros instead of whitespace
%number Maximum field width;
%.number Precision of a floating point number;
printf function prints a formatted string.
Format Specifiers
Conversion Definition
%b Unsigned binary integer
%c Character
%d, i Decimal number
%e Floating point number in scientific notation
%E Floating point number in scientific notation using capital E
%f, %F Floating point number
%g Floating point number using either e or f conversion, whichever takes the least space
%G Floating point number using either e or f conversion, whichever takes the least space
%ld, %D Long decimal number
%lu, %U Long unsigned decimal number
%lo, %O Long octal number
%p Pointer (hexadecimal)
%s String
%u Unsigned decimal number
%x Hexadecimal number
%X Hexadecimal number using capital X
%lx Long hexidecimal number
%% Print a literal percent sign
print function prints a string or a list of comma-separated words to the Perl filehandle STDOUT.
If successful, the print function returns 1; if not, it returns 0.
The string literal \n adds a newline to the end of the string.
To interpret backslashes, Perl requires that escape sequences like \n be enclosed in double quotes.
print "Hello", "world", "\n";
print "Hello world\n";
print "Hello, $ENV{USER}!\n";
print "Hello, $ENV{USER}!\n";
print "Hello!\n";
print "Hello!\n";
print $INC{'English.pm'};
require English;
print $INC{'English.pm'};
Printing Numeric Literals
#!/usr/bin/perl
# Program to illustrate printing literals
print "The price is $100.\n";
print "The price is \$100.\n";
print "The price is \$",100, ".\n";
print "The binary number is converted to: ",0b10001,".\n";
print "The octal number is converted to: ",0777,".\n";
print "The hexadecimal number is converted to: ",0xAbcF,".\n";
print "The unformatted number is ", 14.56, ".\n";
$now = localtime(); # A Perl function
$name = "A"; # A string is assigned to a Perl variable
print "Today is $now, $name.";
print 'Today is $now, $name.';
Printing Output
#The print and printf functions are built-in functions used to display output.
#The print function arguments consist of a comma-separated list of strings and/or numbers.
#The printf function is used for formatting output.
#Parentheses are not required around the argument list.
#print value, value, value;
#printf ( string format [, mixed args [, mixed ...]] );
print "Hello, world\n";
print "Hello,", " world\n";
print ("this is a test!\n");
print "The the date and time are: ", localtime, "\n";
printf "Hello, world\n";
printf("Meet %s%:Age 5d%:Salary \$10.2f\n", "John", 40, 55000);
Printing String Literals
#!/usr/bin/perl
print "***\tIn double quotes\t***\n"; # Backslash interpretation
print '%%%\t\tIn single quotes\t\t%%%\n'; # All characters are printed as literals
print "\n";
Print only care about the first parenthesis
#!/usr/bin/perl -w
print (3 + 7) * 15, "\n";
print out all pm library location
perl -e "print \"@INC\";"
Print out here document
$display = 1;
if ($display) {
print <<EOD;
This
is
a
"here"
document.
EOD
}
print $]; (Perl version number)
print $];
Prints a welcome statement with escape character
print "3. Welcome ", "to ", "Perl!\n";
Prints a welcome statement with several escape characters
print "Welcome\n to\n\n Perl!\n";
prints out each element of @ARGV separately
#!/usr/bin/perl
use warnings;
use strict;
foreach (@ARGV) {
print "Element: |$_|\n";
}
print sqrt 4;
print sqrt 4;
Print the default variable's ($_) value
foreach ( 'A ', 'J ', 'S ', 'D ' ) {
print;
}
print -t STDIN; #Is it tied to a terminal?
print -t STDIN; #Is it tied to a terminal?
print -z STDIN; #Does it have zero size?
print -z STDIN; #Does it have zero size?
Program to illustrate the use of scalar variables.
#!perl
$a = 5;
print "The value of variable a is: $a\n";
$a = $a + 5;
print "Variable a after adding 5 is: $a\n";
$a *= 2;
print "Variable a after multiplying by 2 is: $a\n";
# using an uninitialized variable in the context of a string
print "Using a variable before initializing: $var\n";
# using an uninitialized variable in a numeric context
$test = $num + 5;
print "Adding uninitialized variable \$num to 5 yields: $test.\n";
# using strings in numeric contexts
$str = "A string value";
$a = $a + $str;
print "Adding a string to an integer yields: $a\n";
$strnum = "15charactersand1";
$c = $a + $strnum;
print "Adding $a to string \"$strnum\" yields: $c\n";
Put all into a parenthesis for print statement
#!/usr/bin/perl -w
print((3 + 7) * 15, "\n");
Put code in a block
#!/usr/bin/perl
use warnings;
{
print "This is a first level block. \n";
{
print " This is a second level block. \n";
}
}
Quick Sum
#!/usr/bin/perl
use warnings;
use strict;
my $total=0;
$total += $_ for @ARGV;
print "The total is $total\n";
Read a line of input from the keyboard
$Console = "con";
open(IN,"$Console") || die "Can't open $Console, $!\n";
$| = 1;
print "Please enter data here: ";
$Input = <IN>;
chop $Input;
print "Input = $Input\n";
close(IN);
Read and set environment variables?
use Env qw(PATH TEMP);
print "\$PATH = $PATH\n";
print "\$TEMP = $TEMP\n";
print "\$ENV{'TEMP'} = $ENV{'TEMP'}\n";
$TEMP = "e:\\temp";
print "\$TEMP = $TEMP\n";
print "\$ENV{'TEMP'} = $ENV{'TEMP'}\n";
Read a single character from the keyboard
use Term::ReadKey;
print "Please enter character here: ";
ReadMode("cbreak",STDIN);
$Input = getc(STDIN);
ReadMode("original",STDIN);
print "$Input\nInput = $Input\n";
Reading from STDIN
#STDIN, STDOUT, and STDERR refers stdin, stdout, and stderr.
#By default, these filehandles are associated with your terminal.
#When printing output to the terminal screen, STDOUT is used.
#When printing errors, STDERR is used.
#When assigning user input to a variable, STDIN is used.
#The Perl <> input operator encloses the STDIN filehandle.
#The next line of standard input can be read from the keyboard.
#If you don't want the newline, then you have to "chomp" it off.
# Getting a line of input from the keyboard.
print "What is your name? ";
$name = <STDIN>;
print "What is your father's name? ";
$paname=<>;
print "Hello respected one, $paname";
Read input from keyboard
print "Please enter first number:\n";
$number1 = <STDIN>;
chomp $number1;
print "Please enter second number:\n";
$number2 = <STDIN>;
chomp $number2;
$sum = $number1 + $number2;
print "The sum is $sum.\n";
Read lines from supplied filenames
#!/usr/bin/perl
use warnings;
use strict;
my @words;
while (<>) {
# read each line into $_ in turn
push @words, split; # split $_ into words and store them
}
print "Found ", scalar(@words), " words in input \n";
Read name from console
#!C:\perl\bin
print "Enter your name: ";
$myname = <STDIN>;
print "Hello $myname \n";
Read three lines of text from standard input
#!/usr/bin/perl
use strict;
for (1..3) {
last unless defined (my $line = <>);
warn "Read_three got: $line";
}
Read user input
#!/usr/bin/perl
print "What is your name? ";
chomp($name = <STDIN>); # Program waits for user input from keyboard
print "$name, are you ready?";
chomp($response = <STDIN>);
$response=lc($response); # response is converted to lowercase
if($response eq "yes" or $response eq "y"){
print "Great! Let's get started learning Perl by example.\n";
}
else{
print "O.K. Try again later.\n";
}
$now = localtime; # Use a Perl function to get the date and time
print "$name, you ran this script on $now.\n";
Read user input and use if statement to check it
#!/usr/bin/perl
use warnings;
use strict;
my $weather = "good";
print "How hot is it, in degrees? ";
my $temperature = <STDIN>;
print "And how many emails left to reply to? ";
my $work = <STDIN>;
chomp($weather, $temperature);
if ($weather eq "snowing") {
print "OK, let's go!\n";
} elsif ($weather eq "raining") {
print "No way, sorry, I'm staying in.\n";
} elsif ($temperature < 18) {
print "Too cold for me!\n";
} elsif ($work > 30) {
print "Sorry just too busy.\n";
} else {
print "Well, why not?\n";
}
Redirect STDIN to error.log
open(STDIN, "<error.log") || die "Problem redirecting STDIN.";
Reference element in @_
sub addem
{
$value1 = shift @_;
if ($#_ > 0) {
$value2 = @_[1];
} else {
$value2 = 1;
}
print "$value1 + $value2 = " . ($value1 + $value2);
}
addem(2);
Reference variable by package name
#!/usr/bin/perl -w
$main::name = "A";
$Tom::name = "B";
$Jack::name = "C";
print "\$name in package main is $name\n";
print "\$name in package Tom is $Tom::name\n";
print "\$name in package Jack is $Jack::name\n";
Relational Operators and Numeric Values
Operator Example Meaning
> $x > $y $x is greater than $y
>= $x >= $y $x is greater than or equal to $y
< $x < $y $x is less than $y
<= $x <= $y $x is less than or equal to $y
Relational Operators and String Values
#Operator Example Meaning
#gt $str1 gt $str2 $str1 is greater than $str2
#ge $str1 ge $str2 $str1 is greater than or equal to $str2
#lt $str1 lt $str2 $str1 is less than $str2
#le $str1 le $str2 $str1 is less than or equal to $str2
$fruit1 = "pear";
$fruit2 = "peaR";
$result = $fruit1 gt $fruit2;
print "$result\n";
$result = $fruit1 lt $fruit2;
print "$result\n";
Relational Operators demo
$x = 5;
$y = 4;
$result = $x > $y;
print "$result\n";
$result = $x < $y;
print $result;
Remainder and power
#!C:\perl\bin
$b = 7;
$size = 25;
$othervalue = 12;
$mass = 10;
$acceleration = 14;
$minutes = 600;
$num = 12;
$a = $b + 5;
$size = $size - $othervalue;
print "\$size = $size\n\n";
$speed = $mass * $acceleration;
print "\$speed = $speed\n\n";
$hours = $minutes / 60;
print "\$hours = $hours\n\n";
$remainder = 5 % 2;
print "\$remainder = $remainder\n\n";
$square = $num ** 2;
print "\$square = $square\n\n";
Require another perl file
# parent.pl
#!/usr/bin/perl
use warnings;
use strict;
my $text = "This is the parent";
require 'child.pl';
print "$text \n"; # produces "This is the parent"
Requires the package created above and calls the subroutine declared within it:
package Nothing;
sub doNothing
{
print "This package does nothing!\n";
}
1;
#########################################
#!/usr/local/bin/perl -w
# Use the package nothing.
require "Nothing.pl";
# Call the subroutine doNothing inside the package Nothing.
Nothing::doNothing();
Resetting array base
@a = (1, 2, 3);
print "Array \@a = @a\n";
print "Element \@a[0] = $a[0]\n";
print "Resetting array base...\n";
$[ = 1;
print "Element \@a[1] = $a[1]\n";
Resulting Values of Bitwise Operators
$x $y $x & $y $x | $y $x ^ $y
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Retrieving the Entire Pattern: $&
#!/usr/local/bin/perl
while ($line = <>) {
while ($line =~ /\d/g) {
$digitcount[$&]++;
}
}
print ("Totals for each digit:\n");
for ($i = 0; $i <= 9; $i++) {
print ("$i: $digitcount[$i]\n");
}
Saving in the $& special scalar
$_=5000;
s/$_/$& * 2/e;
print "The new value is $_\.n";
$_="knock at heaven's door.\n";
s/knock/"$&," x 2 . "$&ing"/ei;
print "He's $_";
Scalar alias
#!/usr/bin/perl -w
use strict;
our $scalar1="one";
*scalar2=\$scalar1;
our $scalar2="two";
print $scalar1;
Scalar, array, and hash output
$salary=50000; # Scalar assignment
@months=('Mar', 'Apr', 'May'); # Array assignment
%states= ( # Hash assignment
'CA' => 'California',
'NM' => 'New Mexico',
);
print "$salary\n";
print "@months\n";
print "$months[0], $months[1], $months[2]\n";
print "$states{'CA'}, $states{'NM'}\n";
print $x + 3, "\n";
print "***$name***\n";
Scalars (Denoted by $)
#To assign a scalar to another scalar, you simply say:
# $string1 = "This is a scalar";
# or
# $string1 = $string2;
scalar value interpolation
#!/usr/bin/perl -w
use strict;
my $name = "Tom";
print "My name is $name\n";
Scalar variables hold a single number or string and are preceded by a dollar sign ($).
$number = 150;
$name = "Tom";
$today = localtime();
Scope and block
#!/usr/bin/perl
our $scalar = "global";
print "\$scalar is a $scalar variable\n";
{
my $scalar = "lexical";
print "\$scalar is now a $scalar variable\n";
}
print "\$scalar is a $scalar variable again\n";
Scope change
#!/usr/bin/perl -w
use strict;
package First;
our $scalar = "first";
print $scalar;
package Second;
print $scalar;
our $scalar = "second";
print $scalar;
package Third; {
our $scalar = "inner";
print $scalar;
}
print $scalar;
Scope of Variables: Variables used in subroutines are global by default
sub bye {
print "Bye $name\n";
$name="Tom";
}
$name="Tom";
print "Hello to you and yours!\n";
&bye;
print "Out of the subroutine. Hello $name.\n";# $name is now Tom
&bye;
Set the $/ and chomp
#!/usr/bin/perl
my $string1 = "This is a string";
print "\$string1 is \"$string1\"";
print "\n\nChanging \$/ to \"g\" \n\n";
$/ = "g";
# Removing last character if it is equal to "g"
chomp ( $string1 );
print "The new \$string1 is \"$string1\"\n";
shift: defaults to shifting @ARGV
#!/usr/bin/perl -w
use strict;
sub version {
print "version\n";
}
my $option = shift; # defaults to shifting @ARGV
version() if $option eq "-v" or $option eq "--version";
print "Hello, world.\n";
Short-circuit operators
#!/usr/bin/perl
$num1=50;
$num2=100;
$num3=0;
print $num1 && $num3, "\n";
print $num3 && $num1, "\n";
print $num1 && $num2, "\n";
print $num2 && $num1, "\n\n";
print $num1 || $num3, "\n";
print $num3 || $num1, "\n";
print $num1 || $num2, "\n";
print $num2 || $num1, "\n";
$SIG{__DIE__}
$SIG{__DIE__} = sub {print "This script is about to die!\n"};
die;
$SIG{__WARN__} = 'IGNORE';
$SIG{__WARN__} = 'IGNORE';
warn;
#$SIG{__WARN__} = sub {};
#$SIG{__WARN__} = 'DEFAULT';
#$SIG{__WARN__} = sub {die};
$SIG{__WARN__} = sub {die "Warning: $_[0]"};
$SIG{__WARN__} = sub {die "Warning: $_[0]"};
warn;
Simple calculation with scalar variable
$x = 2;
$x = $x + 2;
print $x;
$x = $x - 2;
print $x;
$x = $x * 5;
print $x;
$^S: is inside eval
if ($^S) {
print "Inside eval.\n";
} else {
print "Outside eval.\n";
}
eval {
if ($^S) {
print "Inside eval.\n";
} else {
print "Outside eval.\n";
}
}
Special Hashes: The %ENV Hash
The %ENV hash contains the environment variables.
If you change the value of %ENV, you will alter the environment.
#!/usr/bin/perl
foreach $key (keys(%ENV){
print "$key\n";
}
print "\nYour login name $ENV{'LOGNAME'}\n";
$pwd=$ENV{'PWD'};
print "\n", $pwd, "\n";
Special Literals
Special Literals
Literal Description
__LINE__ Represents the current line number
__FILE__ Represents the current filename
__END__ Represents the logical end of the script; trailing garbage is ignored
__DATA__ Represents a special filehandle
__PACKAGE__ Represents the current package; default package is main
print "The script is called", __FILE__, "and we are on line number ",__LINE__,"\n";
Special Variables
#!/usr/local/bin/perl -w
use English;
# Print out the process id using the standard variable.
print "PID : Standard: $$ ";
# Print out the process id using the English value assigned.
print "English: $PROCESS_ID\n";
# Print out the real user ID using the standard variable.
print "Real User ID: Standard: $< ";
# Print out the real user id using the English value assigned.
print "English: $REAL_USER_ID\n";
# Print out the Perl version using the standard variable.
print "Perl Version: Standard: $] ";
# Print out the Perl version using the English value assigned.
print "English: $PERL_VERSION\n";
Splitting up $_
while(<DATA>){
@line=split(":"); # or split (":", $_);
print "$line[0]\n";
}
__DATA__
Splitting up $_ and creating an unnamed list
while(<DATA>){
($name,$phone,$address,$bd,$sal)=split(":");
print "$name\t $phone\n" ;
}
Square $var
#!/usr/bin/perl
$var=0;
$var **= 2; # Square $var
print "\$var squared is $var\n";
Standard input
#The script gets user input from the STDIN (standard input) "file."
#STDIN normally comes from your keyboard.
#STDIN, STDOUT and STDERR are the pre-defined file handles.
#In scalar context, the command reads a single line of text from a file.
#In array context, the <STDIN> command would read in an entire file.
$lang = <STDIN>;
chomp($lang);
print $lang;
Statements, Whitespace, and Linebreaks
# 5+4*2 is the same as 5 + 4 * 2;
print "This is a Perl statement.";
print "This
is
also
a Perl
statement.";
Stick with one variable and modify its value
#!/usr/bin/perl
use warnings;
$a = 6 * 9;
print "Six nines are ", $a, "\n";
$a = $a + 3;
print "Plus three is ", $a, "\n";
$a = $a / 3;
print "All over three is ", $a, "\n";
$a = $a + 1;
print "Add one is ", $a, "\n";
$! stores the error message
use File::Copy;
copy("nonexistant.pl","new.pl"); #Try to copy a non-existant file.
print "$!\n";
$_ stores the user input
while (<>) {
print "Too big!\n" if $_ > 10;
}
String- and numeric-comparison operators.
String operator Comparison operation Equivalent numeric operator
lt Less than <
gt Greater than >
eq Equal to ==
le Less than or equal to <=
ge Greater than or equal to >=
ne Not equal to !=
cmp Compare, returning 1, 0, or -1 <=>
Here are some examples of string-comparison operators in action:
$result = "aaa" lt "bbb"; # result is true
$result = "aaa" gt "bbb"; # result is false
$result = "aaa" eq "bbb"; # result is false
$result = "aaa" le "aaa"; # result is true
$result = "aaa" ge "bbb"; # result is false
$result = "aaa" ne "aaa"; # result is false
$result = "aaa" cmp "bbb"; # result is -1
String comparison operator
print "Please enter letters from k to m\n";
while (<>) {
chop;
if ($_ lt 'k' or $_ gt 'm') {
print "Please enter letters from k to m\n";
} else {
print "Thank you - let's have another!\n";
}
}
Subtract 1 from $var
#!/usr/bin/perl
$var=0;
$var -= 1; # Subtract 1 from $var
print "\$var -= 1 is $var\n";
surrounding FINIS with single quotes
#the text that follows will be treated literally, turning off the meaning of any special characters.
$price=1000;
print <<'FINIS';
$500."
FINIS
Switches between packages.
#!/usr/local/bin/perl
package pack1;
$var = 26;
package pack2;
$var = 34;
package pack1;
print ("$var\n");
Syntac of using a module
The Importing Module What It Means
use myModule; myModule is loaded.
use myModule qw( fun2 ); myModule is loaded; fun2 is imported.
use myModule(); myModule is loaded, no symbols imported.
use myModule qw(:group1 !:group2 ); myModule imports symbols from group1 (See:%EXPORT_TAGS hash, above) but not symbols from group2.
use myModule qw(:group1 !fun2); myModule imports symbols from group1, not the symbol fun2.
use myModule qw(/^fu/); myModule imports symbols whose names start with fu.
Syntax for the print Function
syntax Description
print FILEHANDLE list; Print to FILEHANDLE the data in list
print FILEHANDLE; Print the contents of the default special variable $_ to FILEHANDLE
print list; Print to the default selected file handle the data in list
print; Print to the default selected file handle (STDOUT at startup) the contents of the default special variable $_
System variables that control how write sends output to a file
$~ contains the name of the print format.
$^ contains the name of the print format being used as a page header.
$= contains the number of lines per printed page.
$- contains the number of lines left on the current page.
printf formats an individual line of text using format specifiers.
Test of open and die with $!.
#!/usr/bin/perl -w
$filename = "nofile";
open(TMP, $filename)
or die "Can't open \"$filename\" due to $! ";
The 'and' Operator
#!/usr/bin/perl
use warnings;
print"51 ANDed with 85 gives us", 51 & 85, "\n";
The Argument Vector @ARGV
#Gets the rights for all files listed on the command line
use Win32::FileSecurity;
foreach( @ARGV ) {
next unless -e $_ ;
if ( Win32::FileSecurity::Get( $_, \%hash ) ) {
while( ($name, $mask) = each %hash ) {
print "$name:\n\t";
Win32::FileSecurity::EnumerateRights( $mask, \@happy );
print join( "\n\t", @happy ), "\n";
}
} else {
print( "Error #", int( $! ), ": $!" );
}
}
The ARGV Array: command line parameters
#!/usr/bin/perl
die "$0 requires an argument.\n" if $#ARGV < 0 ;# Must have at least one argument
print "@ARGV\n"; # Print all arguments
print "$ARGV[0]\n"; # Print first argument
print "$ARGV[1]\n"; # Print second argument
print "There are ", $#ARGV + 1," arguments.\n";# $#ARGV is the last subscript
print "$ARGV[$#ARGV] is the last one.\n"; # Print last arg
The assignment operators.
Operator Operations performed
= Assignment only
+= Addition and assignment
-= Subtraction and assignment
*= Multiplication and assignment
/= Division and assignment
%= Remainder and assignment
**= Exponentiation and assignment
&= Bitwise AND and assignment
|= Bitwise OR and assignment
^= Bitwise XOR and assignment
The autoincrement operator
#!/usr/bin/perl
use warnings;
$a = "A9"; print ++$a, "\n";
$a = "bc"; print ++$a, "\n";
$a = "Zc"; print ++$a, "\n";
$a = "z9"; print ++$a, "\n";
$a = "9z"; print ++$a, "\n";
The backslash operator means "adddress of"
#!/bin/perl
$num=5;
$p = \$num;
print 'The address assigned $p is ', $p, "\n";
print "The value stored at that address is $$p \n";
The Bit-Manipulation Operators
The following bit-manipulation operators are supported in Perl:
The & (bitwise AND) operator
The | (bitwise OR) operator
The ^ (bitwise XOR or "exclusive or") operator
The ~ (bitwise NOT) operator
The << (left shift) and >> (right shift) operators
The code executes a line of code you type as long as that line doesn't start with a #
while (<>) {eval if !/^#/}
#The script executes it like this:
#How does this script look with the $_ back in?
while ($_ = <>) {eval $_ if !($_ =~ /^#/)}
The -c Switch checks the Perl syntax without actually executing the Perl commands
perl -c script.pl
//File: script.pl
print "hello';
print "hello";
The diagnostics Pragma
This pragma enhances the warning messages to a more verbose explanation
use diagnostics;
print "Hello there'; # Unmatched quote
print "We are on line number ", __LINE__,"\n";
The environment associative array: Associative arrays %ENV holds your system's environment variables.
#!/usr/bin/perl -w
# Access environment variables.
@key_names = keys(%ENV);
print "Key names are: @key_names\n\n";
# Now, access each element from the list.
foreach $key (@key_names) {
print "$key=$ENV{$key}\n";
}
The -e switch executes Perl statements at the command line instead of from a script.
$ perl -e 'print "hello dolly\n";' # UNIX/Linux
$ perl -e "print qq/hello dolly\n/;" # Windows and UNIX/Linux
The @* field
#!/usr/bin/perl
use warnings;
use strict;
my $name = 'Mary';
my $letters = 'SWM';
my $phone = '(111)111-2222';
my $itemA = <<'DONE';
lINE 1
Line 2
Line 3
DONE
write();
$name = 'Jack';
$letters = 'EEE';
$phone = '(222)222-1111';
$itemA = <<'DONE';
Line 1
Line 2
Line 3
DONE
write();
$name = 'Tom';
$letters = 'SSS';
$phone = '';
$itemA = 'itemA';
write();
format STDOUT =
Name: @<<<<<<<<<<<<<<<<<<< letters: @<<<<< phone: @<<<<<<<<<<<<
$name, $letters, $phone
@*
$itemA
.
The filehandle STDOUT must be specified if strings are not quoted.
print STDOUT Hello, world, "\n";
The following functions and operators work with the $_ variable by default:
The pattern-matching operator
The substitution operator
The translation operator
The <> operator, if it appears in a while or for conditional expression
The chop function
The print function
The study function
The HTML tags are embedded in the here document to avoid using multiple print statements
#!/bin/perl
print <<EOF; #here document in a CGI script
Content-type: text/html
<HTML><HEAD><TITLE>Title</TITLE></HEAD>
<H1><CENTER>Dear!!</CENTER></H1>
</HTML>
EOF
The @ISA Array and Calling Methods
{ package Grandpa;
$name = "Tom";
sub greetme {
print "$Child::name, $name.\n";
}
}
{ package Parent;
# This package is empty
}
{ package Child;
$name = "Baby";
print "Hi I'm $name in the Child Package here.\n";
Parent->greetme();
}
The list separator is a comma
my $listSeparator = $";
(@array) = (1..5, "A", "B", "C");
$" = ',' ;
print STDOUT "The list separator is a comma.\n";
print STDOUT "@array\n\n";
The list separator is the empty string
my $listSeparator = $";
(@array) = (1..5, "A", "B", "C");
$" = '' ;
print STDOUT "The list separator is the empty string.\n";
print STDOUT "@array\n\n";
$" = $listSeparator;
print STDOUT "The list separator returned to its previous value.\n";
print STDOUT "@array\n\n";
The -n Switch: print the contents of a file or search for a line that contains a particular pattern
$ perl -ne 'print;' yourtextFile # Windows: use double quotes
$ perl -ne 'print if /^Igor/;' yourTextFile
The numeric comparison operator evaluates its operands
#returning a -1 if the first operand is less than the second operand,
# 0 if the numbers are equal, or
# 1 if the first operand is greater than the second.
$x = 5;
$y = 4;
$result = $x == $y;
print "$result\n";
$result = $x != $y;
print "$result\n";
$result = $x <=> $y;
print "$result\n";
$result = $y <=> $x;
print "$result\n";
The Pattern-Matching Operator and $_
#By default, the pattern-matching operator examines the value stored in $_.
#This means that you can leave out the =~ operator if you are searching $_:
print ("hi") if ($_ =~ /abc/);
print ("hi") if (/abc/); # these two are the same
The print command prints out the text you provide it
print "Wow.\n"; # This is a comment in a line.
%, the remainder, or 'modulo' operator
#!/usr/bin/perl
use warnings;
print"15 divided by 6 is exactly ", 15 / 6, "\n";
print "That's a remainder of ", 15 % 6, "\n";
The $_ Scalar Variable
#The $_ is used as the default pattern space for searches and to hold the current line.
#functions such as chomp, split, and print use $_ as an argument.
$_ = "Donald Duck";
print; # The value of $_ is printed
The shift operator returns an undefined value if the array has no more elements.
#!/usr/bin/perl -w
# Get first argument.
$arg = shift(@ARGV);
# Loop while there is an argument.
while (defined $arg) {
print "$arg\n";
# Get next argument.
$arg = shift(@ARGV);
}
The %SIG hash sets signal handlers for signals.
The %SIG array contains values only for signals set within the Perl script.
#!/usr/bin/perl
sub handler{
local($sig) = @_; # First argument is signal name
print "Caught SIG$sig -- shutting down\n";
exit(0);
}
$SIG{'INT'} = 'handler'; # Catch <Ctrl>-c
print "Here I am!\n";
sleep(10);
$SIG{'INT'}='DEFAULT';
$SIG{'INT'}='IGNORE';
The startup line tells the shell where Perl is located.
#!/usr/bin/perl
# My first Perl script
print "Hello to you and yours!\n";
The strict Pragma
#!/bin/perl
use strict "refs";
$animal="dog";
$dog="Tom";
print "${$animal}\n";
eval "\$$animal='Tom';";
print "${$animal}?\n";
The strict Pragma and Words
If your program disobeys the restrictions placed on it, it won't compile.
#!/usr/bin/perl
# Program: stricts.test
# Script to demonstrate the strict pragma
use strict "subs";
$name = SS; # Unquoted word
print "Hi $name.\n";
The Substitution Operator and $_
The substitution operator uses the $_ variable if you do not specify a variable using =~.
For example, the following statement replaces the first occurrence of abc in $_ with def:
s/abc/def/;
The warnings Pragma and the -w Switch
#The -w switch warns you
#You can use the -w switch either as a command-line option to Perl, as
perl -w <scriptname>
#!/usr/bin/perl
# Scriptname: warnme
print STDOUT Ellie, what\'s up?;
$ perl -w warnme
The -w option passed to the perl command generates a warning about the code itself.
#!/usr/bin/perl -w
# Test of open and die with $!.
$filename = "nofile";
open(TMP, $filename) or die "Can't open \"$filename\" due to $! ";
This code should be stored in the file Mymodule.pm.
#Code that creates a Perl module.
#/usr/local/bin/perl
package Mymodule;
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(myfunc1 myfunc2);
@EXPORT_OK = qw($myvar1 $myvar2);
sub myfunc1 {
$myvar1 += 1;
}
sub myfunc2 {
$myvar2 += 2;
}
three-way-comparison becomes cmp.
#!/usr/bin/perl
#
use warnings;
print"Which came first, the chicken or the egg? ";
print "chicken" cmp "egg", "\n";
print "Are dogs greater than cats? ";
print "dog" gt "cat", "\n";
print "Is ^ less than + ? ";
print "^" lt "+", "\n";
time - $^T
while (<>) {
$time = time - $^T;
print "You started this script $time seconds ago.\n";
}
To force perl to perform an operation of lower precedence first, use brackets
#!/usr/bin/perl
use warnings;
print(3 + 7) * 15;
To list all .pm files by using the @INC array
#!/usr/bin/perl -w
@dir_list = @INC;
$i = 0;
while ($i <= $#dir_list) {
$dir = $dir_list[$i];
listPMFile($dir);
$i++;
}
sub listPMFile {
my($dir) = $_[0];
my(@list);
my($new_dir);
my($filename);
my($name);
if ($dir eq ".") {
return;
}
chdir( $dir );
@list = glob("\*");
foreach $filename (@list) {
# Check if file ends with .pm
if ($filename =~ /\.pm$/ ) {
$name = $filename;
$name =~ s/\.pm$//;
print "$dir/$name\n";
}
# Check if is a directory.
if ( -d $filename ) {
$new_dir = $dir . "/" . $filename;
# Append directory name onto dir list.
$pos = $#dir_list + 1;
$dir_list[$pos] = $new_dir;
}
}
}
To quit the ppm command
PPM> quit
Quit!
To set a variable, use the = operator.
# Setting scalar variables.
$var = "Text";
$number_var = 44.5;
print $var;
print $number_var;
undef $/;
undef $/;
open HANDLE, "yourFile.txt";
$text = <HANDLE>;
print $text;
undef a variable
$variable1 = 5;
print $variable1;
undef $variable1;
$variable1
Use constant PI
use constant PI => 4 * atan2 1, 1;
print "Pi = ", PI;
Use eq to compare strings
#!c:\perl\bin
$string1="B";
$string2="E";
if($string1 eq $string2)
{
print "Those two names are the same! \n";
}else{
print "Those two strings are not the same! \n";
}
Use parentheses wherever possible to force precedence.
#!/usr/local/bin/perl -w
print "Enter the first number : ";
my $num1 = <STDIN>; chomp $num1;
print "Enter the second number: ";
my $num2 = <STDIN>; chomp $num2;
print "Enter the third number : ";
my $num3 = <STDIN>; chomp $num3;
# A*B-C
my $answer = $num1 * $num2 - $num3;
print "$num1 * $num2 - $num3 = $answer \n";
# (A*B)-C
$answer = ($num1 * $num2) - $num3;
print "($num1 * $num2) - $num3 = $answer \n";
# A*(B-C)
$answer = $num1 * ($num2 - $num3);
print "$num1 * ($num2 - $num3) = $answer \n";
Uses the same name inside and outside a foreach statement.
#!/usr/local/bin/perl
$temp = 1;
@list = ("This", "is", "a", "list", "of", "words");
print ("Here are the words in the list: \n");
foreach $temp (@list) {
print ("$temp ");
}
print("\n");
print("The value of temp is now $temp\n");
use strict;
#!/usr/bin/perl -w
use strict;
$x = 10;
print $x;
'use strict' and subroutine
#!/usr/bin/perl -w
use strict;
setup;
sub setup {
print "This is some program, version 0.1\n";
}
use strict Pragma
use strict "vars";
my $name = "Tom"; #All variables are lexical in scope
our @friends = qw(Tom Stefan Bin Marie);
our $newspaper = "The Globe";
print "$name and $friends[0] read the $newspaper.\n";
use strict 'refs';
use strict 'refs';
if ($^H && 2 ) {
print "You're using use strict 'refs'\n"
};
use strict 'subs';
use strict 'subs';
if ($^H && 512 ) {print "You're using use strict 'subs'\n"};
use strict 'vars';
use strict 'vars';
if ($^H && 1024 ) {print "You're using use strict 'vars'\n"};
'use strict' with package
#!/usr/bin/perl -w
use strict;
$main::x = 10;
print $main::x, "\n";
Use while loop to display all entries in ENV
while(($key, $value) = each(%ENV)) {
print "$key => $value\n";
}
Using a Module from the Standard Perl Library in a Script)
#!/bin/perl
use Carp qw(cluck);
print "Number: ";
$grade = <STDIN>;
try($grade); # Call subroutine
sub try{
my($number)=@_;
cluck "Illegal value: " if $number < 0 || $number > 100;
}
print "That was just a warning. Program continues here.\n";
Using & operator
print "hello\n" & '______';
Using and (&&) operator with if statement
use integer;
$variable = 5;
if ($variable < 6 && $variable > 4) {
print "Yes, it's five.\n";
}
Using a Perl 5 Module from the Standard Perl Library
#!/usr/bin/perl
use English; # Use English words to replace special Perl variables
print "The pid is $PROCESS_ID.\n";
print "The pid is $PID.\n";
print "The real uid $REAL_USER_ID.\n";
print "This version of perl is $PERL_VERSION.\n";
Using Assignment Operators on Scalar Variables
#How do you place data in a scalar variable?
#You use the assignment operator.
$variable1 = 5;
#String assignments work much the same way:
$variable1 = "Hello there!";
#Besides single assignments, you can create multiple assignments in the same statement like this:
$x = $y = $z = 1;
print join (", ", $x, $y, $z);
Using $_ as the array index
#!/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 auto-increment operator for a string
#!/usr/bin/perl -w
$a = "bz"; print ++$a, "\n";
$a = "Zz"; print ++$a, "\n";
Using auto-increment operator for a string with digits
#!/usr/bin/perl -w
$a = "A9"; print ++$a, "\n";
$a = "z9"; print ++$a, "\n";
$a = "9z"; print ++$a, "\n";
Using bare blocks to form a multiple-selection structure.
print "Enter your guess (1-3): ";
$guess = <STDIN>;
BLOCK: { # start of bare block
if ( $guess == 1 ) {
print "Right!\n";
last BLOCK; # jump to end of BLOCK
}
if ( $guess == 2 ) {
print "Close!\n";
last BLOCK; # jump to end of BLOCK
}
if ( $guess == 3 ) {
print "Wrong!\n";
last BLOCK; # jump to end of BLOCK
}
# default case;
{
print "Please re-enter your guess (1-3): ";
$guess = <STDIN>;
redo BLOCK; # jump to beginning of BLOCK
}
}
Using '|'(bar) operator
print "h l o\n" | " e l ";
Using boolean operator (and &&) to connect the comparison operator
#!/usr/bin/perl -w
print "Test one: ", 6 > 3 && 3 > 4, "\n";
print "Test two: ", 6 > 3 and 3 > 4, "\n";
Using comma in a print statement
#!/usr/bin/perl -w
print 69 + 118, "\n";
Using defined.
#!/usr/local/bin/perl
$array[2] = 14;
$array[4] = "hello";
for ($i = 0; $i <= 5; $i++) {
if (defined ($array[$i])) {
print ("element ", $i+1, " is defined\n");
}
}
Using 'defined' keyword in if statement
#!/usr/bin/perl -w
use strict;
my ($a, $b);
$b = 10;
if (defined $a) {
print "\$a has a value.\n";
}
if (defined $b) {
print "\$b has a value.\n";
}
Using diamond operator with while statement
while (<>) {
print;
}
Using diamond sign to read from keyboard
#!/usr/bin/perl -w
use strict;
while (<>) {
print "text read: $_"
}
Using @_ directly
sub addone
{
++@_[0];
}
$value = 1;
addone($value);
print "The value of \$value = $value.\n";
Using $_ (dollar underscore)
#!/usr/bin/perl -w
use strict;
print "contents of @ARGV:\n";
print "[$_]\n" foreach @ARGV;
print "\$0: $0\n";
Using /e modifier to evaluate
#!usr/bin/perl
use warnings;
use strict;
my $string = "abc ABC.";
print "$string\n";
$string =~ s/(\bw\w+\b)/uc($1)/e;
print "$string\n";
Using -e option to execute the perl statement
perl -e "print \"@INC\";"
Using eq in statement
#!/usr/bin/perl -w
use strict;
my $password = "foxtrot";
print "Enter the password: ";
my $guess = <STDIN>;
chomp $guess;
if ($password eq $guess) {
print "Pass, friend.\n";
}
Using __LINE__ to output line number
perl -e "print __LINE__;"
Using ne in if statement
#!/usr/bin/perl -w
use strict;
my $password = "foxtrot";
print "Enter the password: ";
my $guess = <STDIN>;
chomp $guess;
if ($password ne $guess) {
die "Go away, imposter!\n";
}
Using '^' operator
print "h l o\n" ^ " e l ";
Using Perl Built-in Functions
print("Hello, there.\n");
print "Hello, there.\n";
Using Perl to Create Your Own Module
#Me.pm Module)
package Me;
use strict; use warnings;
require 5.6;
require Exporter;
our @ISA=qw(Exporter);
our @EXPORT_OK=qw(hello);
sub hello {
my($name)=shift;
print "Hi there, $name.\n"
};
1;
# Program name: main.perl
#!/usr/bin/perl
use lib ("/Modules");
use Me qw(hello);
&hello ("Tom");
Using scalar reference
*MAXFILES = \100;
print "$MAXFILES\n";
Using shift to process the command-line arguments.
#!/usr/local/bin/perl
while (1) {
$currarg = shift;
last if (!defined($currarg));
print ("$currarg\n");
}
Using %SIG to define our own signal handlers
#!/usr/bin/perl
use warnings;
use strict;
my $count = 3;
$| = 1;
$SIG{ 'INT' } = \&stop;
while ( $count ) {
print( "Hi!" );
print( "\n" );
sleep( 1 );
}
sub stop
{
$SIG{ 'INT' } = \&stop;
$count--;
print( "$count\n" );
unless ( $count ) {
print( "line...\n" );
}
}
Using the Default Variable $_
#When you use the construct <STDIN> without assigning, Perl assigns that return value to a variable named $_.
#Many Perl functions use this special variable, called the default variable.
#You can use the print function without specifying a variable at all to print the contents of $_.
while($_ = <STDIN>) {
print $_;
}
Using the diamond operator with @ARGV
#!usr/bin/perl
use strict;
use warnings;
print while ( <> );
Using the $;(dollar and semicolon) variable.
#!/usr/local/bin/perl
$; = "::";
$array{"hello","there"} = 46;
$test1 = $array{"hello","there"};
$test2 = $array{"hello::there"};
print ("$test1 $test2\n");
Using the if statement to check the command line parameters
#!/usr/bin/perl -w
use strict;
sub version {
print "version\n";
}
my $option = shift; # defaults to shifting @ARGV
version() if $option eq "-v" or $option eq "--version";
print "Hello, world.\n";
Using the -n option.
#!/usr/local/bin/perl -n
# input line is stored in the system variable $_
$line = $_;
chop ($line);
printf ("* %-52s *\n", $line);
Using the package keyword to change the package context
#!/usr/bin/perl -w
$main::name = "A";
$Tom::name = "B";
$Jack::name = "C";
print "\$name in package main is $name\n";
package Tom;
print "\$name in package Tom is $name\n";
package Jack;
print "\$name in package Jack is $name\n";
package main;
Using the print Function
To print text to a file, including to STDOUT, you use the print function.
The print function has these forms:
print FILEHANDLE LIST
print LIST
print
If you don't specify a file handle, STDOUT is used.
If you don't specify a list of items to print, the print function prints whatever is in the special Perl variable $_ to the output channel.
The $_ variable is the default variable that holds input from the input channel.
print "Hello!\n";
Using the special Perl variable $! in the message passed to die.
# This variable, $!, holds information about the error that occurred.
#!/usr/bin/perl -w
# Test of open and die with $!.
$filename = "nofile";
open(TMP, $filename) or die "Can't open \"$filename\" due to $! ";
Using the strict Pragma
#A pragma is a module that triggers a compiler to behave in a certain way.
#The strict pragma can be used to prevent the use of global variables in a program.
#The 'our' built-in is used when you need a global variable but still want to use the strict pragma
use strict "vars";
my $name = "Tom"; # my (lexical) variables are okay
@friends = qw(Tom A B C); # global variables not allowed
local $newspaper = "The Globe"; # local variables are not allowed
print "My name is $name and our friends are @friends.\n";
Using the @_ to reference the parameter
#!/usr/bin/perl -w
use strict;
my $var = 10;
print "before: $var\n";
change_var($var);
print "after: $var\n";
sub change_var {
my($v) = @_;
# or: my $v = shift;
print "in change_var() before: $v\n";
++$v;
print "in change_var() after: $v\n";
}
Using the $. variable.
#!/usr/local/bin/perl
open (FILE1, "file1") ||
die ("Can't open file1\n");
open (FILE2, "file2") ||
die ("Can't open file2\n");
$input = <FILE1>;
$input = <FILE1>;
print ("line number is $.\n");
$input = <FILE2>;
print ("line number is $.\n");
$input = <FILE1>;
print ("line number is $.\n");
Using $, to set the separator for print command
$, = ';';
print 1, 2, 3;
Using tr to convert all file names passed in to uppercase
#!/usr/bin/perl -w
foreach $filename (@ARGV) {
$newname = $filename;
$newname =~ tr/a-z/A-Z/;
if ($newname ne $filename) {
if ( -e $newname ) {
print "ERROR: Won't clobber existing $newname.\n";
} else {
print "Renaming $filename to $newname.\n";
rename($filename, $newname) or die "Cannot rename $filename to $newname due to $!";
}
}
}
Using two statements with -e option
perl -e "print \"Hello \";" -e "print \"there\";"
Using undef to represent an unusual condition.
#!/usr/local/bin/perl
print ("Enter the number to divide:\n");
$value1 = <STDIN>;
chop ($value1);
print ("Enter the number to divide by:\n");
$value2 = <STDIN>;
chop ($value2);
$result = &safe_division($value1, $value2);
if (defined($result)) {
print ("The result is $result.\n");
} else {
print ("Can't divide by zero.\n");
}
sub safe_division {
local ($dividend, $divisor) = @_;
local ($result);
$result = ($divisor == 0) ? undef :
$dividend / $divisor;
}
Using variable with -e option
perl -e "$text = \"Hello there\";" -e "print $text;"
Using $_ variable with while statement
while(<>) {
print;
}
while (<>) {
for (split) {
s/m/y/g;
print;
}
}
while ($_ = <>) {
for $_ (split / /, $_) {
$_ =~ s/m/y/g;
print $_;
}
}
'#!/usr/bin/perl -w ' tells the perl command to turn on extra warnings with the -w option.
#!/usr/bin/perl -w
$i = 0;
until ($i >= 10) {
print "Iteration $i.\n";
$i++;
}
! $v1 && $v2
$v1 = 1;
$v2 = 0;
$v3 = ! $v1 && $v2;
if($v3) {
print "\$v3 is true.";
}
else {
print "\$v3 is false.";
}
Variables and Arrays
Perl's variables fall into three major types: scalars, arrays, and associative arrays or hashes.
Perl differentiates variable names based on the first character $, @, or % respectively.
Syntax Meaning
NAME File handle or directory handle
$NAME Scalar variable.
@NAME Array indexed by position number.
%NAME Associative array, also called hash, indexed by string.
NAME() Invoke the subroutine NAME.
&NAME Invoke the subroutine NAME.
*NAME Everything named NAME.
Scalar variables hold a single value, either a text string or a number.
You can set the same variable to hold either text or numeric data, and you can switch by setting a string variable to hold a number, and vice versa.
Verify an installation using ppm
PPM> verify Tk
Package 'Tk' is up to date.
Verify the total number of the command line parameter
#!/usr/bin/perl -w
# argv2.pl
use strict;
print "program arguments:\n";
my $i = 0;
while ($i <= $#ARGV) {
print "argument $i: $ARGV[$i]\n";
$i++;
}
$^W: Check the '-w switch'
if (!$^W) {
print "You should use the -w switch.";
}
open FILEHANDLE, "<file.dat";
print FILEHANDLE "Hello!";
close FILEHANDLE;
While block
#!/usr/bin/perl
use warnings;
use strict;
while (my $line = <>) {
last if $line =~/quit/;
print "You entered: $line";
}
print "Bye! \n";
Working with $_ usually makes programming much easier, but more confusing to the uninitiated
#In the following example, every statement uses $_ implicitly.
while (<>) {
for (split) {
s/m/y/g;
print;
}
}
#It breaks the line you type into words, loops over those words, converts all m's to y's, and prints the result like this.
#So how does this code look if you put the $_ default variable back in explicitly?
while ($_ = <>) {
for $_ (split / /, $_) {
$_ =~ s/m/y/g;
print $_;
}
}
x 4 says that the text within the here document will be printed four times.
print << x 4;
Here's to a new day.
Cheers!
$^X: get the Perl execuatable file name
print $^X;
You can combine operators such as +, -, and * with the assignment operator
$x += 2;
$x -= 2;
$x *= 5;
You can omit the STDIN altogether
#If you just use the angle brackets < and > alone, without specifying any file handle, STDIN is used by default.
while ($temp = <>) {
print $temp;
}
You can pass a list of items to print, where you separate the list items with commas:
print "Hello ", "there!\n";
You display the current line of execution in a Perl script by referring to it with the __LINE__ token.
print __LINE__;
You display the name of the current file with the __FILE__ token
print __FILE__;
You display the name of the current Perl package with __PACKAGE__.
print __PACKAGE__;
You have to tell Perl which packages you intend to use, with the use command:
# use packagename;
# For example:
# use File::Copy;
#!/usr/bin/perl -w
use File::Copy;
$input = "text.txt";
$output = "text1.txt";
copy($input, $output) or die
"Can't copy $input to $output due to $!.";
Your package
#!/usr/bin/perl
use warnings;
use strict;
package MyPackage;
$package_variable = "This variable is in 'MyPackage'"; # ERROR