Upload
prakash
View
220
Download
0
Embed Size (px)
7/31/2019 38875080 Perl Scripting
1/112
Perl ScriptingPerl Scripting
7/31/2019 38875080 Perl Scripting
2/112
Course ContentsCourse Contents
1. Introduction to Perl
2. Working with scalars (numbers & strings)
3. Operators and functions
4. Conditions & loops
5. Working with lists (arrays & hashes)
6. Sub-routines
7. Regular expressions
7/31/2019 38875080 Perl Scripting
3/112
Contd..Contd..
8. references and complex data structures
9. debugging in Perl
10. Packages & Modules
11. managing files and directories
12. working with files and I/O
13. handling databases in Perl
7/31/2019 38875080 Perl Scripting
4/112
1. Introduction to Perl1. Introduction to Perl
y Perl stands for Practical Extraction and
Report Language.
y Perl is a mixture of UNIX tools (sed, grep,
awk etc.), Shell Scripting, C and ObjectOriented features.
y Perl was created by Larry Wall. It is now not
owned by any single Organization. Perl isdefined and maintained by a group of
volunteer programmers including LarryWall.
7/31/2019 38875080 Perl Scripting
5/112
Features ofPerlFeatures ofPerl
1. Perl is free
2. Perl is both a compiled and interpretedlanguage
3. Perl is portable
4. Perl can interface with other languages
5. Perl is easy to use and debug
7/31/2019 38875080 Perl Scripting
6/112
How to get PerlHow to get Perl
Perl can be downloaded from the Internetthru www.perl.org (or) www.perl.com
The current version of Perl is 5.10.0.
Perl is available on different platforms,Unix,Windows, MacOS etc.
7/31/2019 38875080 Perl Scripting
7/112
Writing the first programWriting the first program
$ vi first.pl
# program to print a message
print Hello, World\n ;
To run the program,
$ perl first.pl
7/31/2019 38875080 Perl Scripting
8/112
About the ProgramAbout the Program
Any line that starts with a #, is a comment
To display messages, print command is used
Every perl statement must end with a ;
7/31/2019 38875080 Perl Scripting
9/112
Command Line OptionsCommand Line Options
To know the current version of Perl
$ perl v
To check the syntax errors only but does not
run the script
$ perl c first.pl
To turn on the warnings
$ perl w first.pl
7/31/2019 38875080 Perl Scripting
10/112
7/31/2019 38875080 Perl Scripting
11/112
Data TypesData Types
Perl has two types of data:
1. scalars: data consisting of a single thing
ex: Numbers, Strings, References
2. lists: data consisting of a collection of
single things or scalars
ex:Arrays, Hashes
7/31/2019 38875080 Perl Scripting
12/112
2.Scalars2.Scalars
A) Numbers:
4 45e-4
3.2 0xbeef
.234567 0125. 1_234_456
10E2
Perl does not differentiate between integersand floats, signed or unsigned, or short andlong numbers. Perl converts between thenumber types as needed in our scripts
7/31/2019 38875080 Perl Scripting
13/112
ScalarsScalars
B) Strings :A string is zero or more characters
surrounded by single quotes ( )
or by double quotes ()
Escape sequences are used forstring formatting in print function.
\n new line
\t tab\b backspace
7/31/2019 38875080 Perl Scripting
14/112
ScalarsScalars
\a bell sound
\0nn octal
\0xnn hexadecimal
\l make next letter lower case
\u make next letter upper case
\L make all the following letters lower
\U make all the following letters upper
7/31/2019 38875080 Perl Scripting
15/112
ScalarsScalars
Converting between numbers and strings:Since, numbers and strings are scalar data,
they are interchangeable.
ex: 5 + 14 gives 19
foo + 5 gives 5
23abc + 7 gives 30
7/31/2019 38875080 Perl Scripting
16/112
Scalar VariablesScalar Variables
$a=5;$a=$b=5;$a=$b=5,$c=7;
$s=abc;$t=xyz;Rules for variable names:1.should start with a letter, underscore
2.case sensitive3.can be up to 255 characters.We dont have to declare or initialize variables in thebeginning.
7/31/2019 38875080 Perl Scripting
17/112
InputInput
Reading scalar values from Keyboard:
$a=;
chomp ($a);When we enter values from the keyboard,
\n
is automatically attached to the input value.To remove \n from the input, we use chomp
function.
7/31/2019 38875080 Perl Scripting
18/112
OutputOutput
Displaying the values on the screen:
print ($a\n);
printf (%.2f\n,$b);
$c=sprintf(%.2f,$b);
7/31/2019 38875080 Perl Scripting
19/112
3.Operators & Functions3.Operators & Functions
Arithmetic operators:
+ (addition),
- (subtraction),
* (multiplication),
/ (division),
% (remainder),
** (exponent)
7/31/2019 38875080 Perl Scripting
20/112
7/31/2019 38875080 Perl Scripting
21/112
OperatorsOperators
Assignment Operators:
+=, -=,*=, /=, %=, **=
Increment and Decrement Operators:
++, --
Conditional Operator:
exp1?exp2:exp3
7/31/2019 38875080 Perl Scripting
22/112
OperatorsOperators
Bitwise Operators:
String catenation operator:
.
String repetition operator:
x
7/31/2019 38875080 Perl Scripting
23/112
OperatorsOperators
Quoting the strings:
Single quotes: q/how are you/
Double quotes: qq/how are you/
General quotes: qw (abc);
7/31/2019 38875080 Perl Scripting
24/112
NumberFunctionsNumberFunctions
abs () absolute value
int () converts to integer
sin () sine value
cos () cosine value
rand () random number
exp () e to the power of
atan2 () arctangentord () ascii number
sqrt () square root
7/31/2019 38875080 Perl Scripting
25/112
String FunctionsString Functions
chr () ascii characterindex () returns the pos. of chr.length () length
reverse () reverses a scalarrindex () reverse indexsubstr () substringlc () lowercaseconversionuc () upper caseconversionlcfirst () first character loweruc first() first character upper
7/31/2019 38875080 Perl Scripting
26/112
4.Conditions and Loops4.Conditions and Loops
if
if (condition) { statements}
if (condition)
{statements}
else
{statements}
7/31/2019 38875080 Perl Scripting
27/112
Conditions and LoopsConditions and Loops
if (condition)
{
statements
}
elsif (condition)
{
statements}
7/31/2019 38875080 Perl Scripting
28/112
Conditions and LoopsConditions and Loops
unless
unless (condition)
{statements
}
7/31/2019 38875080 Perl Scripting
29/112
Conditions and LoopsConditions and Loops
while
while (condition)
{statements
}
7/31/2019 38875080 Perl Scripting
30/112
Conditions and LoopsConditions and Loops
until
until (condition)
{statements
}
7/31/2019 38875080 Perl Scripting
31/112
Conditions and LoopsConditions and Loops
do
do {statements}
while (condition);
do {statements}
until (condition);
7/31/2019 38875080 Perl Scripting
32/112
Conditions and LoopsConditions and Loops
for
for (init; test; change){
statements
}
7/31/2019 38875080 Perl Scripting
33/112
Conditions and LoopsConditions and Loops
foreach
foreach value (list){
statements
}
7/31/2019 38875080 Perl Scripting
34/112
Conditions and LoopsConditions and Loops
Infinite loopswhile ()
{
statements}
for (;;)
{statements
}
7/31/2019 38875080 Perl Scripting
35/112
Conditions and LoopsConditions and Loops
break from a control statement
lastcontinue
next
7/31/2019 38875080 Perl Scripting
36/112
Conditions and LoopsConditions and Loops
$_ variable
It is the default placeholder for scalar
valuesexample
foreach (`dir`)
{print ($_\n);
}
7/31/2019 38875080 Perl Scripting
37/112
Conditions and LoopsConditions and Loops
switchuse Switch;
switch ($value){
case 1 {print 1; }.
else {print 0 ;}}
7/31/2019 38875080 Perl Scripting
38/112
5.Arrays andHashes5.Arrays andHashes
CreatingArrays:
@nums = (1,2,3,4);
@nums = (1..4);@strings = (ab , cd , ef );
@strings = (a ,z);
@strings = ();
@combine=(@nums, @strings);
7/31/2019 38875080 Perl Scripting
39/112
Arrays andHashesArrays andHashes
Printing theArray:
print (@nums\n);
print (@strings\n);
print (@combine\n);Processing each element:
foreach $x (@nums)
{print ($x\n);
}
7/31/2019 38875080 Perl Scripting
40/112
Arrays andHashesArrays andHashes
AccessingArray elements:
$nums[3];
The subscript starts from 0 to n-1NegativeArray Indexes:
$nums[-1];
Negative array subscripts will countback
from the end of the array.
7/31/2019 38875080 Perl Scripting
41/112
Arrays andHashesArrays andHashes
GrowingArrays:@nums=(1..4);
$nums[6]=7;
Result is 1,2,3,4,undefined, undefined,7
Finding the end of theArray:
$end=$#nums;
Finding the length of theArray:
$len=@nums;
7/31/2019 38875080 Perl Scripting
42/112
Arrays andHashesArrays andHashes
Sorting theArray:
cmp (strings), < = > (numbers)
@sorted=sort {$a cmp $b} @strings;@sorted=sort {$a < = > $b} @nums;
Reversing theArray:
@new=reverse (@old);
7/31/2019 38875080 Perl Scripting
43/112
Arrays andHashesArrays andHashes
push and pop functions allow you toadd or remove elements from the end
of the list
$new=push (@nums,5);
$new1=pop (@nums);
7/31/2019 38875080 Perl Scripting
44/112
7/31/2019 38875080 Perl Scripting
45/112
Arrays andHashesArrays andHashes
slice creates pieces of the Array@array=(1..10);@slice=@array[0,1,2];
splitting the data into anArray$strings=12 23 43;@nums=split( ,$strings);
joining the data from anArray$strings=join(+, @nums);
7/31/2019 38875080 Perl Scripting
46/112
Arrays andHashesArrays andHashes
Creating a Hash:%hash=(key=>value, key=>value, key=>value);Ex:
%pairs=(red=>255, blue=>355, green=>455);Accessing Hash Elements:
$hash {$key};Ex: $pairs {red};
Printing the Hash:print %hash;
Ex: print %pairs;
7/31/2019 38875080 Perl Scripting
47/112
Arrays andHashesArrays andHashes
Processing a Hash:foreach $key (sort keys %hash){
print $hash {$key}\n;}while (($key, $value) = each (%hash){
print $hash {$key} \n;}
7/31/2019 38875080 Perl Scripting
48/112
Arrays andHashesArrays andHashes
Ex:
foreach $key (sort keys %pairs)
{
print $pairs {$key}\n;}
or
while (($key,$value) = each (%pairs))
{print $pairs {$key} \n;
}
7/31/2019 38875080 Perl Scripting
49/112
Arrays andHashesArrays andHashes
Adding an element to a Hash:
$hash {$key} = $value;
Ex:
$pairs {yellow}=555;
Deleting an element from a Hash:
delete ($hash {
$key});Ex:
delete ($pairs {red});
7/31/2019 38875080 Perl Scripting
50/112
Arrays andHashesArrays andHashes
Inverting a Hash:
%new=reverse %hash;
Ex:
%newpairs = reverse %pairs;
Finding the no. of keys in a Hash:
$n=keys %hash;
Ex:
$n=keys %pairs;
7/31/2019 38875080 Perl Scripting
51/112
6.Subroutines6.Subroutines
The terms function and subroutine areentirely equivalent in Perl.
Perl handles three types of functions.
1. Built-in: These are the functions that are
defined by the standard Perl library that we
can use any where in our Perl scripts.
7/31/2019 38875080 Perl Scripting
52/112
SubroutinesSubroutines
2. Additional: These are the functions that areavailable to us by using the additional Perlmodules or libraries, written by other Perl
programmers, that we can load in at the startof the script.
3. Subroutines: These are user definedfunctions. By convention, the term subroutine
is used to identify the function as user definedone.
7/31/2019 38875080 Perl Scripting
53/112
SubroutinesSubroutines
Defining & Calling basic subroutines:print enter temperature in forenheight \n;
chomp ($f=);
&cal();print The result is $cel\n;
sub cal ()
{
$cel=($f-32)*5/9;
}
7/31/2019 38875080 Perl Scripting
54/112
SubroutinesSubroutines
Returning values from a subroutine:$sum=&cal();print The sum is $sum\n;
sub cal (){
print enter two nos. \n;chomp ($n1=);
chomp ($n2=);return ($n1 + $n2);
}
7/31/2019 38875080 Perl Scripting
55/112
SubroutinesSubroutines
Using local variables inside a subroutine:We can create local variables inside a
subroutine usingmy modifier.
$sum=&cal();print The sum is $sum\n;sub cal (){
my ($n1,$n2);print enter two nos. \n;chomp ($n1=);chomp ($n2=);
7/31/2019 38875080 Perl Scripting
56/112
SubroutinesSubroutines
PassingArguments to a subroutine:$sum=&cal(3,5);print The sum is $sum\n;sub cal (){ my ($m,$n)= @_;
my $p=1;while ($n>0){ $p=$p*$m;
$n--;}
return ($p);}
7/31/2019 38875080 Perl Scripting
57/112
SubroutinesSubroutines
Anonymous subroutines:These are subroutines without namesand they operate sort of like pointers
to functions in C.
7/31/2019 38875080 Perl Scripting
58/112
7.REGULAR EXPRESSIONS7.REGULAR EXPRESSIONS
REGULAR EXPRESSION OPERATORS:
m//, s///, tr///
@x = grep /x/, @words;
PATTERN MATCHING OPERATORS:
=~, !~
REs:
abc exact character sequence
7/31/2019 38875080 Perl Scripting
59/112
REGULAR EXPRESSIONSREGULAR EXPRESSIONS
^abc abc at the beginning
abc$ abc at the ending
a|b a or b
ab {2,4}c a followed by 2,3,4 bs
followed by c
ab{2,}c a followed by at least 2 bs
followed by c
7/31/2019 38875080 Perl Scripting
60/112
REGULAR EXPRESSIONSREGULAR EXPRESSIONS
ab*c a followed by zero or more
bs followed by c
ab+c a followed by one or more
bs followed by cab?c a followed by optional b
followed by c (abc or ac)
a.c an a followed by any singlecharacter (no newline) followed by c
7/31/2019 38875080 Perl Scripting
61/112
REGULAR EXPRESSIONSREGULAR EXPRESSIONS
a\.c a.c exactly
[abc] any one of a , b or c
[Aa]bc Abc or abc
[^abc] not containing a or b or c
7/31/2019 38875080 Perl Scripting
62/112
8.References8.References
A reference is similar to a pointer in C.The reference itself is a scalar, it can be
assigned to a scalar variable, printed, added
to, passed to subroutine etc. To find outwhat the reference points to, we can
dereference the reference.
Creating a reference for a scalar:
$str=This is a string;
$strref=\$str;
7/31/2019 38875080 Perl Scripting
63/112
ReferencesReferences
Dereferencing a scalar reference:$originalstr=$$strref;Creating a reference for anArray:
@array=(1..10);$arrayref=\@array;Dereferencing an array reference:@originalarray=@$arrayref;
To refer to individual elements:$originalarray[0] or $$arrayref[0];
7/31/2019 38875080 Perl Scripting
64/112
ReferencesReferences
Creating a reference for a hash:
%hash=(a=>255,b=>355,c=>455);
$hashref=\%hash;
Dereferencing a hash reference:
%originalhash=%$hashref;
To refer to individual keys:
$originalhash{a} or $$hashref{a};
7/31/2019 38875080 Perl Scripting
65/112
ReferencesReferences
Creating a reference for a subroutine:$subref=\&mysub;Dereferencing a subroutine:
$result=&$subref(3,5);Creating anonymous subroutines:$subref=sub {.};
Dereferencing a subroutine:$result=&$subref();
7/31/2019 38875080 Perl Scripting
66/112
ReferencesReferences
Anonymous data: The term anonymous meanswithout a name.Anonymous data refers to data(usually arrays, hashes and subroutines) that wecan only access through a reference i.e. the datadoes not have an associated variable name. Usinganonymous data, we can create nested datastructures such as,
1.Arrays ofArrays2. Hashes ofArrays
3. Hashes of Hashes
7/31/2019 38875080 Perl Scripting
67/112
ReferencesReferences
Arrays ofArrays:
@array= ( [0,1,2],
[23,33,43],
[53,54,55]
);
Referring to individual elements:
$array[0][1] or $array[0]->[1]
7/31/2019 38875080 Perl Scripting
68/112
ReferencesReferences
Hashes ofArrays:
%hash= ( b=>[0,1,2],
g=> [23,33,43],
r=>[53,54,55]
);
Referring to individual elements:
$hash{b}[1] or $array{b}->[1]
7/31/2019 38875080 Perl Scripting
69/112
ReferencesReferences
Hashes of Hashes:
%hash=(a=>{x=>0,y=>1,z=>2},
b=>{l=>3,m=>4,n=>5},
c=>{p=>53,q=>54,r=>55}
);
Referring to individual elements:
$hash{a}{x} or $array{a}->{x}
7/31/2019 38875080 Perl Scripting
70/112
9.Debugging in Perl9.Debugging in Perl
Perl comes with a source level debugger.The debugger can help us track downsubtle problems in our code.
We shall see,
1. how to start and run the debugger
2. step through the execution of the script3. trace the execution of the script
4. list the source in various ways
7/31/2019 38875080 Perl Scripting
71/112
Debugging in PerlDebugging in Perl
5. print out the values of the variables6. set the breakpoints
To invoke the debugger,$ perl d temp.plAfter the display of some messages, we seemain::(temp.pl:1): system (cls);
DB
7/31/2019 38875080 Perl Scripting
72/112
Debugging in PerlDebugging in Perl
DB debugger prompt with
command number
main package nametemp.pl script name
1 line no. of the script
system (cls) line in the script to be run
7/31/2019 38875080 Perl Scripting
73/112
Debugging in PerlDebugging in Perl
Debugger Commands:
n runs a line of the script, silently
executes subroutines
s runs a line of the script, steps intosubroutines
l list 10 lines after the current line
- list the lines before the currentline
x prints the value of any scalar, list
7/31/2019 38875080 Perl Scripting
74/112
Debugging in PerlDebugging in Perl
Debugger Commands:
X print out all the variables in the
current package
V same as X except it takes anoptional name of a package
r stops stepping thru the subroutine,
executes rest of it, returns to thecalling place.
c runs the script without stepping thru
7/31/2019 38875080 Perl Scripting
75/112
Debugging in PerlDebugging in Perl
Debugger Commands:
b to set a break point
S prints all the available subroutines
t turns tracing on or off
h help
|h pause help with breaks
!3 refers to the command no. 3
H -3 lists last 3 commands
7/31/2019 38875080 Perl Scripting
76/112
Debugging in PerlDebugging in Perl
Debugger Commands:
T show the stack trace
w shows a window around the
current line
L lists all break points
d deletes a break point
D deletes all set break points
7/31/2019 38875080 Perl Scripting
77/112
10.PACKAGES & MODULES10.PACKAGES & MODULES
What is a Package?A package is a namespace It is a space thatprovides its own global scope for identifiers. Itfunctions as a private programming space.
How to create Packages?
We can place the code for a Package in itsown file, or in multiple files, or even createseveral packages in the same file. To switchinto another package, we use the packagestatement.
7/31/2019 38875080 Perl Scripting
78/112
PACKAGES & MODULESPACKAGES & MODULES
$ vi packages.plpackage package1;BEGIN {}
$x=1;sub subroutine1 { print one\n ;}return 1;
END {}
7/31/2019 38875080 Perl Scripting
79/112
PACKAGES & MODULESPACKAGES & MODULES
$ vi prg1.plrequire packages.pl;
package1::subroutine1();
print $package1::x;To run,
$ perl prg1.pl
To know in which package we are,print __PACKAGE__;
7/31/2019 38875080 Perl Scripting
80/112
PACKAGES & MODULESPACKAGES & MODULES
Splitting a Package across files:
$ vi file1.pl
package package1;BEGIN {}sub sub1 { print hello\n; }return 1;
END {}
7/31/2019 38875080 Perl Scripting
81/112
PACKAGES & MODULESPACKAGES & MODULES
$ vi file2.pl
package package1;
BEGIN {}sub sub2 { print bye\n; }
return 1;
END {}
7/31/2019 38875080 Perl Scripting
82/112
PACKAGES & MODULESPACKAGES & MODULES
$ vi original.plrequire file1.pl;
require file2.pl;
package1::sub1();package1::sub2();
The result is,
hellobye
7/31/2019 38875080 Perl Scripting
83/112
7/31/2019 38875080 Perl Scripting
84/112
PACKAGES & MODULESPACKAGES & MODULES
Our Declaration: Our declaration sets globalscope across packages, i.e. variable of one
package can be accessed in another package.
$ vi packages.plpackage package1;
our $data=1;
sub sub1 { print hello\n; }return 1
END {}
7/31/2019 38875080 Perl Scripting
85/112
PACKAGES & MODULESPACKAGES & MODULES
package package2;
sub sub2 { print $data\n; }
return 1;
END {}
To run this,
package1::sub1();
package2::sub2();
7/31/2019 38875080 Perl Scripting
86/112
PACKAGES & MODULESPACKAGES & MODULES
Creating Modules: A Perl Module is just apackage in which the package is defined in a
file with the same name as the package and
has the extension pm.
This allows subroutine names automatically
exported to the code when we include a
Module.
7/31/2019 38875080 Perl Scripting
87/112
PACKAGES & MODULESPACKAGES & MODULES
$ vi Module1.pmpackage Module1;BEGIN
{ use Exporter();@ISA=qw (Exporter);@EXPORT=qw (&subroutine1&subroutine2);
}sub subroutine1 { print hello\n ;}sub subroutine2 { print thanks\n; }return 1;
7/31/2019 38875080 Perl Scripting
88/112
PACKAGES & MODULESPACKAGES & MODULES
$ vi final.pluse Module1;
subroutine1();
subroutine2();$ perl final.pl;
CPAN:There are literally hundreds of
modules that have been developed foruse
with Perl.
7/31/2019 38875080 Perl Scripting
89/112
PACKAGES & MODULESPACKAGES & MODULES
Many are available with the Perl Distributionitself. CPAN (Comprehensive Perl Archive
Network) serves as a repository for user
developed modules. An up-to-date survey of
the contents of CPAN can be found at
www.perl.com
However, there are two drawbacks to the
CPAN modules. The first is that we have todownload, build and install modules before
they can be used. Some modules may require
7/31/2019 38875080 Perl Scripting
90/112
PACKAGES & MODULESPACKAGES & MODULES
compilation which means that we need aworking C compiler.
Secondly, most of the CPAN modules are
developed for UNIX Perl. For installingWindows specific modules, there is a special
tool called ppm.
C:\> ppm
PRAGMAS:These are the modules that
7/31/2019 38875080 Perl Scripting
91/112
PACKAGES & MODULESPACKAGES & MODULES
provide instructions for Perl to behave at bothcompile time and run time.
ex:
subs:allows you to pre-declare subroutine names.
vars:
allows you to pre-declare global variables sothat they can be accepted under strict
pragma.
7/31/2019 38875080 Perl Scripting
92/112
PACKAGES & MODULESPACKAGES & MODULES
strict:disallows bare words, global variablesand symbolic references.
integer:
allows only integer arithmetic.
constant:
allows to create constant variables atcompile time.
7/31/2019 38875080 Perl Scripting
93/112
PACKAGES & MODULESPACKAGES & MODULES
Global variable: Any variable that is notexplicitly declared with my or local,automatically becomes a global variable
and is available at any point in that script.Any variable declared in a block with my
or local becomes a local variable to that
block.Difference between my and local:
7/31/2019 38875080 Perl Scripting
94/112
PACKAGES & MODULESPACKAGES & MODULES
A my variable is only available to the code upuntil the nearest enclosing block or subroutinedefinition. If we call another subroutine withinthat one, the second subroutine will not have
access to those variables. Local variablesdeclared with local are available to the codeinside that block and subroutine and to thenested subroutines called from the same
subroutine.
7/31/2019 38875080 Perl Scripting
95/112
7/31/2019 38875080 Perl Scripting
96/112
MANAGING FILES & DIRECTORIESMANAGING FILES & DIRECTORIES
Removing files & links:unlink temp, config, foo;
Other file commands:
chmod changing the file permissionschown changing the owner of the file
fileno returns the file descriptor
utime changes the time stamp
7/31/2019 38875080 Perl Scripting
97/112
MANAGING FILES & DIRECTORIESMANAGING FILES & DIRECTORIES
Directory Commands:chdir:chdir images;use Cwd;$curr=cwd();print $curr\n;
File Listing (File Globbing):@files=;while () {
print $_ ,\n;
7/31/2019 38875080 Perl Scripting
98/112
MANAGING FILES & DIRECTORIESMANAGING FILES & DIRECTORIES
Directory Commands:mkdir:
mkdir temp, 0777;
rmdir:
rmdir temp;
Perl and the Environment: Perlenvironment variables are stored in aspecial hash called %ENV.
7/31/2019 38875080 Perl Scripting
99/112
MANAGING FILES & DIRECTORIESMANAGING FILES & DIRECTORIES
Environment Variables are commonly inupper case.
To view all the EnvironmentVariables,
foreach $key (keys %ENV)
{
print $key -> $ENV {$key} \n;
}
7/31/2019 38875080 Perl Scripting
100/112
MANAGING FILES & DIRECTORIESMANAGING FILES & DIRECTORIES
To run OS commands,system (ls);
$ls=`ls`;
7/31/2019 38875080 Perl Scripting
101/112
WORKINGWITHFILES & I/OWORKINGWITHFILES & I/O
Creating a file:open (FH,>myfile) or die can not create\n;
Reading a file:
while ()
{
.
}
7/31/2019 38875080 Perl Scripting
102/112
WORKINGWITHFILES & I/OWORKINGWITHFILES & I/O
Writing to a file:print FH $input\n;
Closing a file:
close FH;open options:
> writing
< reading+> read and write
7/31/2019 38875080 Perl Scripting
103/112
WORKINGWITHFILES & I/OWORKINGWITHFILES & I/O
File Tests:-d directory ?
-e file exists ?
-f plain file ?-l symbolic link ?
-r readable ?
-s ? Big is the file ?-w writable ?
7/31/2019 38875080 Perl Scripting
104/112
WORKINGWITHFILES & I/OWORKINGWITHFILES & I/O
File Tests:-x executable ?
-z empty file ?
-B binary file ?-T text file ?
Command line arguments:
Command line arguments are stored in aspecial list @ARGV.
7/31/2019 38875080 Perl Scripting
105/112
WORKINGWITHFILES & I/OWORKINGWITHFILES & I/O
foreach $arg (@ARGV) {print $arg \n;
}
Use the DBI Module
7/31/2019 38875080 Perl Scripting
106/112
#!/usr/local/bin/perl
use DBI;
Use the DBI Module
Establish connection and get a handle to it
7/31/2019 38875080 Perl Scripting
107/112
#!/usr/local/bin/perl
use DBI;
$db_handle = DBI->connect(DBI:mysql:sanskar_club:sql.njit.edu,
sanskar, pswd) || die (Couldnt connect\n);
Syntax ofDBI->connect()
DBI->connect(data_source, username, password);
data_source will be DBI:driver_name:driver_parameters
For MYSQL at NJIT
driver_name = mysqldriver_parameters = database_username:sql.njit.eduusername = ucid/club account namepassword = afs password
Establish connection and get a handle to it
Prepare an SQL query
7/31/2019 38875080 Perl Scripting
108/112
#!/usr/local/bin/perl
use DBI;
$db_handle = DBI->connect(DBI:mysql:sanskar_club:sql.njit.edu,
sanskar, pswd) || die (Couldnt connect\n);
$stmt_handle = $db_handle->prepare("SELECT name, email, numpeople,accomdetails FROM user_detail");
Prepare an SQL query
Execute the SQL query
7/31/2019 38875080 Perl Scripting
109/112
#!/usr/local/bin/perl
use DBI;
$db_handle = DBI->connect(DBI:mysql:sanskar_club:sql.njit.edu,
sanskar, pswd) || die (Couldnt connect\n);
$stmt_handle = $db_handle->prepare("SELECT name, email, numpeople,
accomdetails FROM user_detail");
$stmt_handle ->execute;
Execute the SQL query
Finish with statement handle
7/31/2019 38875080 Perl Scripting
110/112
#!/usr/local/bin/perl
use DBI;
$db_handle = DBI->connect(DBI:mysql:sanskar_club:sql.njit.edu,
sanskar, pswd) || die (Couldnt connect\n);
$stmt_handle = $db_handle->prepare("SELECT name, email, numpeople,accomdetails FROM user_detail");
$stmt_handle ->execute;while (@row = $stmt_handle->fetchrow()) {
foreach $field (@row){
print "$field ";}print \n;
}
$stmt_handle->finish();
Finish withstatement handle
Close the connection
7/31/2019 38875080 Perl Scripting
111/112
#!/usr/local/bin/perl
use DBI;
$db_handle = DBI->connect(DBI:mysql:sanskar_club:sql.njit.edu,
sanskar,pswd) || die (Couldnt connect\n);
$stmt_handle = $db_handle->prepare("SELECT name,email,numpeople,
accomdetails FROM user_detail");$stmt_handle ->execute;
Close the connection
Contd
7/31/2019 38875080 Perl Scripting
112/112
while (@row = $stmt_handle->fetchrow()) {
foreach $field (@row){
print "$field ";
}
print \n;}
$stmt_handle->finish();
$db_handle->disconnect();
Contd..