Monday, June 21, 2010

Perl Introduction

PERL

Scripting Languages Vs Programming Languages

Scripting Language Programming Language
1) It is an Interpreter based Language 1) It is a compiler based Language.
2) Interpreter converts high level instructions into machine language line by line 2) Compiler converts the whole program in single short into machine language.
3) It doesn’t create executable file. 3) It Creates .exe file.
4) No need to compile the program Need to compile the program
5) It takes less code 4) It takes numerous lines of code
6) It greatly reduces development time 5) It increases development time
7) It reduces maintenance of cost 7) It Increases maintenance of cost
PERL-Practical Extraction and Reporting Language

# Perl was originally developed by Larry Wall, a linguist working as a systems administrator for NASA, in 1987, as a general-purpose Unix scripting language to make report processing easier.
# Perl is a high-level, general-purpose, interpreted, dynamic Scripting language.

The home of perl is UNIX
Perl Inherited features from UNIX utilities (awk, sed, grep, Smalltalk, Lisp, C, C++, Pascal and UNIX shell.
Perl written in C language.
Perl is free software.
Perl is open source code.
Perl is highly portable Language (supports 76+ Operating systems, Scripts developed in one operating system allows to run on other operating system with/without modifications.)
Perl supports oops concepts known as object oriented perl.
Perl supports database connectivity.
Perl has given CPAN (Comprehensive Perl Archive Network) modules.website is www.cpan.org
Perl was originally developed for to do manipulations in the text files later it is used in wide range of the following areas
System Administration
Database Administration
Network Programming
Web Development
Software Testing
Hardware Testing
Telecom
Vlsi
Baoinformatics and so on
It is built-in with UNIX and Its flavers like Linux, Solaris etc…
Perl is a case sensitive Language.
Each and every statement should end with (;) semicolon.
Perl is an interpreter based Language.
Extension of perl program is .pl or .plx
Perl supports two types of comments.
Single line comment (#)
Multi line comment
Pod (perl old document)

——

——

Cut

Perl program compilation Process:

Writing a program to display welcome message

#! C:perlbinperl

print “welcome to Perl n”;

print “This is my first program”;

Save with “first.pl”

Running perl Program in Windows

C:perl first.pl

#! It is shebang statement, used for to invoke perl interpreter path.

Running perl Program in UNIX/Linux

$ which perl # it displays location of perl

usr/bin/perl

perl –v # version of perl

$ man perl # help document

$ vi first.pl

#! usr/bin/perl

print “welcome to Perl n”;

print “This is my first program”;

$ perl first.pl

or

$ chmod 755 first.pl

$./first.pl

Chapter-2 (Variables)
Variables

It is a Data name or memory location name.
It is used for to store data value.
Value can change during execution of the program
It is a temporary storage location.
Perl allows implicit variable declaration.
Every variable occupies memory at runtime.
Variables are classified into 3 types

Scalar Variables
Array Variables or List Variables
Hash Variables or Associate Array Variables
1) Scalar Variables

It holds one value.
The value may be Integer or Float or String.
The Variable should begin with $ symbol.
a=10; – wrong

$a=10; – right

2) Array Variables

It is a group of scalar values
It should begin with @ symbol.
3) Hash Array Variables

It is a group of key pair values.
It should begin with % symbol.
1) Scalar Variables

$a=10; # Integer

$b=1.5; # Float

$c=”Gcreddy” #String

$d=”perl is a scripting language” # String

$e=”100” # String

$f=’Perl’ # String

Strings are classified into 3 types

1) Double quoted strings (“ “) or qq with delimiter of any one || or [] or {} or <>

2) Single quoted strings (‘ ‘) or q with delimiter of any one || or [] or {} or <>

3) Back tick / quoted strings (` `) or qx with delimiter of any one || or [] or {} or <>

a) $str=”perl”;

$x= “I like $str”;

print $x;

Output: I like Perl

b) $x= ‘I like $str’;

print $x

Output: I like $str

c) $x= “I like perl n $str”

print $x;

output: I like

Perl

d) $x= ‘I like n $str’;

print $x;

output: I like $x;

e) $str= “I said “Don’t write to disk””; # wrong

$str= “I said |“Don’t write to disk|””; # right

$str= ‘I said “Don’t write to disk”’; # wrong

$str= ‘I said “Don|’t write to disk”’; # right

$str= qq| I said “Don|’t write to disk”|; # right

$str= q|I said “Don’t write to disk”|; # right

f) $x= “Unix/Linux”; # right

$x= qq|Unix/Linux|; # wrong

$x= qq|Unix/Linux|; # right

$x= qq{Unix/Linux}; # wrong

note: qq for variable substitute

q for as it is

qx for OS command

# $x= `dir`;

`md xyz`;

$x= qx|dir|;

print $x;

perl –c pl.pl # compilation ok

Writing output:

Perl p1.pl>a1 # over write

Perl p1.pl>>a2 # add

Perl p1.pl> D:a3 # path

Standard Input / Output Handlers

print () – it used for to write data to the screen

print(“Hello”);

or

print “Hello”;

or

print STDOUT “Hello”;

I/O handlers

1) STDIN

2) STDOUT

3) STDERR

STDIN – It used for to accept input from user

Ex: write a program accepting name and display?

Print “What is your name”;

$name=; or <> # Diamond operator

print “Hello $name, Good morning”;

chmod ($name); # It is a pre-defined function, it deletes the given string lost line character if it is new line.

Ex2: write a program accept 2 integer values and find sum?

Print “Enter a number 1: “;

Chomp ($a= );

Print “Enter a number 2: “;

Chomp ($b= );

$c= $a + $b

print “n $a + $b= $c”;

Chapter-3 (Operators)
1) Arithmetic Operators:

+, -, *, /, %, ** (right to left)

a) $a=10;

$b=20;

print $a + $b;

output: 30

b) $a=10;

$b=25abc;

print $a + $b;

output: 35

a) $a=10;

$b=”abc20;

print $a + $b;

output: 10

d) $a=10;

$b=20abc34;

print $a + $b;

output: 30

e) $a=”perl”;

$b=”gcreddy”;

print $a + $b;

output: 0

f) $a=10;

$b=”25abc”;

print $a + $b;

output: 35

print $a .$b;

output: 1025abc

g) $a=2;

$b=3;

print $a ** $b;

output: 8

h) $a=2;

$b=3;

$c=2;

print $a ** $b ** $c;

output: 512

i) $a=2;

$b=3;

$c=2;

print ($a ** $b) ** $c;

output: 64

2) Relational Operators:

i) Numeric Comparison Operators

<, >, <=, >=, ==, !=, <=>

ii) String Comparison Operators

lt, gt, le, ge, eq, ne, cmp

a) $a=100;

$b=20;

$a>$b;

output: true

$a gt $b;

output: false (ansii nos)

b) $x= “tecno”;

$y= “harika”;

$x gt $y;

output: true

$x > $y;

output: false (0,0)

c) $a=100;

$b=20;

$c= $a<=>$b

if a>b output is 1

ay output is 1

x $b ? print “$a is big” : print “$b is big”;

10) Incremental Operator (++)

$a=10;

$a=$a+1; or $a+=1; or $a++;

11) Detrimental Operators (–)

$a=$a-1; or $a-=1 or $a–;

——————-****—————-****——————

Chapter-4 (Control flow statements)
a) Conditional Statements:

1) Simple if condition

if (condition)

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

2) Simple unless

unless (condition)

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

3) If….else

if (condition)

{

Statements

——–

——–

——–

}

else

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

4) unless….else

unless (condition)

{

Statements

——–

——–

——–

}

else

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

5) if….elseif…else

if (condition)

{

Statements

——–

——–

——–

}

else if (condition)

{

Statements

——–

——–

——–

}

else if (condition)

{

Statements

——–

——–

——–

}

else

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

6) Single line if statement

statement if (condition);

Statements

——–

——–

7) Single line unless statement

statement unless (condition);

Statements

——–

——–

b) Loop Statements:

1) While Loop

while (condition)

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

2) until Loop

until (condition)

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

3) Do while Loop

do

{

Statements

——–

——–

——–

}

while (condition)

{

Statements

——–

——–

——–

}

4) Do until Loop

do

{

Statements

——–

——–

——–

}

until (condition)

{

Statements

——–

——–

——–

}

5) For Loop

for (initiation; condition; increment/decrement)

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

6) Foreach Loop

foreach variable (list of variables)

{

Statements

——–

——–

——–

}

Statements

——–

——–

——–

7) Last keyword:

It is used for to terminate the loop; it is same as break in ‘C’ Language.

While (condition)

{

Statements

——–

——–

last;

——–

——–

}

Statements

——–

——–

——–

Next keyword:

It is a keyword, used for to place control at beginning of the loop. It is same as continue in ‘C’ language.

While (condition)

{

Statements

——–

——–

next;

——–

——–

}

Statements

——–

——–

——–

Examples:
1) Write a program accepting a number and check given number is 3 digit number or not?

Print “Enter a number: “;

Chomp ($n= );

If ($n >=100 && $a <=999) { print “$n is a 3 digit number”; } else { print $n is not a 3 digit number”; 2) Write a program accepting user name and password and check for given user name & password are valid or not? Print “n Enter user name”; Chomp ($uname= );

Print “n Enter password”;

Chomp ($pwd= );

If ($uname eq “tecno” && $pwd eq “soft”

{

print “n welcome to tecnosoft”;

}

else

{

print “n invalid user name or password”;

}

3) Write a program to print numbers 1 to 10?

$num=1;

while ($num ,=10)

{

print “$num n”;

$num++

}

(or)

for ($num=1; $num <= 10; $num++)

{

print “$num n”;

}

(or)

foreach $num(1..10)

{

print “$num n”;

}

(or)

foreach (1..10)

{

print “$_ n”;

}

(or)

foreach (1..10)

{

print ;

}

Note: $_ is Perl special and default variable. If we don’t declare any variable for reading data then Perl will store the value in default variable.

Database Scripts-Part Two

Database Scripts-II

1) Insert Data into a database table using Database Command Object

Dim objCon,objCom
Set objCon=Createobject("ADODB.connection")

objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"

Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon

objCom.CommandText="insert into Emp values('G C Reddy',88233,30000)"
objCom.Execute

objCon.Close
Set objCom=Nothing
Set objCon=Nothing

2) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object

Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i
Set objCon=Createobject("ADODB.connection")

objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"

Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon

Datatable.AddSheet("input")
Datatable.ImportSheet "C:\gcreddy.xls",1,"input"
intRowcount=Datatable.GetSheet("input").GetRowCount
Msgbox intRowcount
For i=1 to intRowcount step 1
DataTable.SetCurrentRow(i)
strEmpName= DataTable.Value(1,"input")
intEmpNo= DataTable.Value(2,"input")
intEmpSal= DataTable.Value(3,"input")
objCom.CommandText="insert into Emp values( '"&strEmpName&" ',"&intEmpNo&","&intEmpSal&")"
objCom.Execute

Next

objCon.Close
Set objCom=Nothing
Set objCon=Nothing

Database Scripts-Part Two

Database Scripts-II

1) Insert Data into a database table using Database Command Object

Dim objCon,objCom
Set objCon=Createobject("ADODB.connection")

objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"

Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon

objCom.CommandText="insert into Emp values('G C Reddy',88233,30000)"
objCom.Execute

objCon.Close
Set objCom=Nothing
Set objCon=Nothing

2) Insert multiple sets of Data (using Excel sheet) into a database table using Database Command Object

Dim objCon,objCom,strEmpName,intEmpNo,intEmpSal,intRowcount,i
Set objCon=Createobject("ADODB.connection")

objCon.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\gcreddy.mdb;"

Set objCom=Createobject("ADODB.Command")
objCom.ActiveConnection=objCon

Datatable.AddSheet("input")
Datatable.ImportSheet "C:\gcreddy.xls",1,"input"
intRowcount=Datatable.GetSheet("input").GetRowCount
Msgbox intRowcount
For i=1 to intRowcount step 1
DataTable.SetCurrentRow(i)
strEmpName= DataTable.Value(1,"input")
intEmpNo= DataTable.Value(2,"input")
intEmpSal= DataTable.Value(3,"input")
objCom.CommandText="insert into Emp values( '"&strEmpName&" ',"&intEmpNo&","&intEmpSal&")"
objCom.Execute

Next

objCon.Close
Set objCom=Nothing
Set objCon=Nothing

Database Scripts-Part One

Database Scripts-I

1) Get Test Data From a Database and use in Data Driven Testing (through Scripting)

1) Dim con,rs
2) Set con=createobject("Adodb.connection")
3) Set rs=createobject("Adodb.recordset")
4) con.provider=("microsoft.jet.oledb.4.0")
5) con.open "C:\Documents and Settings\Administrator\My Documents\Gcreddy.mdb"
6) rs.open "Select * From Login",con
7) While rs.eof <>True
8) SystemUtil.Run "C:\Program Files\Mercury Interactive\QuickTest Professional\samples\flight\app\flight4a.exe"
9) Dialog("Login").Activate
10) Dialog("Login").WinEdit("Agent Name:").Set rs.fields ("Agent")
11) Dialog("Login").WinEdit("Password:").Set rs.fields ("Password")
12) Dialog("Login").WinButton("OK").Click
13) Window("Flight Reservation").Close
14) rs.movenext
15) Wend

2) Exporting Data from a Database to an Excel Sheet

1) Dim con,rs
2) Set con=createobject("adodb.connection")
3) Set rs=createobject("adodb.recordset")
4) con.provider="microsoft.jet.oledb.4.0"
5) con.open"C:\Documents and Settings\admin\My Documents\Gcreddy.mdb"
6) rs.open"select*from Login",con
7) Set ex=createobject("Excel.Application")
8) Set a=ex.workbooks.open("C:\Documents and Settings\admin\My Documents\Gcreddy.xls")
9) Set b=a.worksheets("sheet1")
10) i=1
11) Do While Not rs.EOF
12) b.cells (i,1).value=rs.fields("agent")
13) b.cells(i,2).value=rs.fields("password")
14) rs.movenext
15) i=i+1
16) Loop
17) a.save
18) a.close

3) Exporting Data from a Database to a Text file
Dim objCon,objRs,ObjFso,myFile,myData,rc,r
Set objCon=createobject("Adodb.connection")
Set objRs=createobject("Adodb.Recordset")
set objFso=createobject("Scripting.Filesystemobject")
Set myFile=objFso.OpenTextFile("C:\Documents and Settings\gcr\My Documents\gcreddy.txt",8)
objcon.provider=("Microsoft.jet.oledb.4.0")
objcon.open"C:\Documents and Settings\gcr\My Documents\gcreddy.mdb"
objrs.open "select * from login",objCon
r=1
Do until objRs.EOF
a=objRs.Fields ("Agent")
b=objRs.Fields ("Pwd")
myFile.Writeline a &","& b
r=r+1
objRs.MoveNext
Loop
myFile.Close
objCon.Close

4) Connecting to a SQL Sever database

Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
"Provider=SQLOLEDB;Data Source=atl-sql-01;" & _
"Trusted_Connection=Yes;Initial Catalog=Northwind;" & _
"User ID=fabrikam\kenmyer;Password=34DE6t4G!;"

objRecordSet.Open "SELECT * FROM Customers", _
objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo objRecordSet.RecordCount

5) Open a Database Using a DSN

Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
"Northwind;fabrikam\kenmyer;34ghfn&!j"

objRecordSet.Open "SELECT * FROM Customers", _
objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo objRecordSet.RecordCount


6) Open Two Recordsets


Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")
Set objRecordSet2 = CreateObject("ADODB.Recordset")

objConnection.Open _
"Provider= Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=inventory.mdb"

objRecordSet.Open "SELECT * FROM GeneralProperties Where ComputerName = 'Computer1'", _
objConnection, adOpenStatic, adLockOptimistic

objRecordSet.MoveFirst


objRecordSet2.Open "SELECT * FROM Storage Where ComputerName = 'Computer1'", _
objConnection, adOpenStatic, adLockOptimistic

objRecordSet2.MoveFirst

Do Until objRecordset.EOF
Wscript.Echo objRecordset.Fields.Item("ComputerName")
Wscript.Echo objRecordset.Fields.Item("OSName")
objRecordSet.MoveNext
Loop

Do Until objRecordset2.EOF
Wscript.Echo objRecordset2.Fields.Item("DriveName"), _
objRecordset2.Fields.Item("DriveDescription")
objRecordSet2.MoveNext
Loop

objRecordSet.Close
objRecordSet2.Close
objConnection.Close


7) Searching a Database Using String Criteria

Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

objConnection.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source = eventlogs.mdb"

objRecordSet.Open "SELECT * FROM EventTable " & _
"WHERE Type = 'Error'", objConnection, adOpenStatic, _
adLockOptimistic

objRecordSet.MoveFirst

Wscript.Echo "Number of records: " & objRecordset.RecordCount

objRecordSet.Close
objConnection.Close