osp-ii unit-5
TRANSCRIPT
-
8/2/2019 OSP-II UNIT-5
1/39
1
Open Source ProgrammingBy
Prof. A. VijayaraniSITEVIT
-
8/2/2019 OSP-II UNIT-5
2/39
2
Introduction to PERL, TCL& PYTHON
Unit V
Numbers and Strings Control Statements Lists and Arrays Files Pattern matching Hashes Functions. Introduction to TCL/TK,
Introduction to Python.
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
3/39
3
Introduction to PERLWhat is PERL? Practical Extraction and Report Language Interpreted Language
Optimized for String Manipulation and File I/O Full support for Regular Expressions
RUNNING PERL SCRIPTS - Windows Mode Download ActivePerl and Install it. Put the following in the first line of your script
#!/usr/bin/perl Just run the script from a 'Command Prompt' window as
>perl program_Name.pl
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
4/39
4
Basic SyntaxStatements end with semicolon ;
Comments start with #
Only single line comments
Type the program in a text editor. Save it with
the extension of pl
Sample Program#!/usr/bin/perl
print "Hello, world!\n";
Output:Hello, world
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
5/39
5
A scalar is the simplest kind of data that Perl manipulates.Most scalars are either a number (like 255 or 3.25e20) or a
string of characters (like hello ).
Dont have to declare a variable before access it.
Don't have to declare a variable's type.
A scalar value can be acted upon with operators (like additionor concatenate), generally yielding a scalar result.
Scalar variable used to store scalar value. It is a casesensitive. It has to start with the symbol $.
Scalars can be read from files and devices, and can be writtenout as well.
Scalars
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
6/39
6
Scalars - Numbers
Perl provides different format of numbers like integer,decimal, non-decimal integer (hexadecimal, binary & Octal). Though Perl provides different format, it computes withdouble precision point values.
Sample valid data:
1.25 - decimal255.000 - decimal255.0 - decimal7.25e45 - decimal1234 - integer-40 - integero377 - Octal
ox2AB3 - Hexadecimalob1011 - Binary
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
7/39
7
Scalars - Strings
Strings are sequences of characters (like hello). Strings maycontain any combination of any characters.
In a Single quoted( ) string, every thing is interpreted literally.
In a Double quoted( ) string, variables are expanded.
Sample Valid Strings:Hello12 th avenue
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
8/39
8
Operations on Numbers
>= -> greater than orequal to
%-> modulo division
-> compare, return 1,0, -1
!= -> not equal to** -> exponent
less than or equalto
/-> division
== -> equal to* -> multiplication
> -> greater than- -> subtraction
< -> less than+ -> addition
Relational OperationsArithmetic
operations
Short hand assignment operators are available in PERL.
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
Logical
Operators&& - and
|| - or
! - not
-
8/2/2019 OSP-II UNIT-5
9/39
9
Formatting - Strings
\u converts the first letter into upper case\U converts all characters in a string to upper case
\l - converts the first letter into lower case\L - converts all characters in a string to lower case
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
10/39
10
Operations on Strings
1. Concatenation operation . Dot used to concatenate twostrings
$name1 = VIT;$name2 =University;
$name = $name1 . $name2;Print $name; # output VIT University
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
11/39
11
Operations on Strings
2. String repetition - x used to repeat the string for the given
number of times.Example:
$name1 =VIT;$name2 = $name1 x 3;print $name2; # VITVITVIT
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
12/39
12
Operations on Strings
3. Pattern Matching & Replace - Perl provides to match asubstring and replace it with new substring or remove it.
=~ - tests whether a pattern is matched!~ - tests whether patterns is not matched
m used to match a substrings used to substitute a substirngg Global match or substitutei for case insensitive.
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
13/39
13
Example
$string = "abc123ddDef";$string =~ s/123/456; # replaces 123 with 456Print $string; # abc456ddDef$string =~ s/456//; # replaces 456Print $string; # abcddDef$string=~s/d/s; # replaces 1st character
print $string; # abcsdDef$string=~s/d/s/g; #replaces all dprint $string; # abcssDef$string =~s/d/s/gi; #replaces all d and Dprint $string; # abcsssefif ($string =~m/b/)
print string contains b;else
print string does not have b;
Operations on Strings
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
14/39
14
I/O StatementsInput: Reading from the standard input stream can be done by. Evaluating this operator in a scalar context gives the nextline of input.
Example:
Print Enter your name;$name = ; #gets input from consolechomp($name); #removes \n in $name
Output: The print operator takes a list of values and sendseach item (as a string, of course) to standard output or to
files.
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
15/39
15
Control Statements - IFIf- statement used to take decision and branches the control basedon that.
Syntax:If (condition)
{ true part;}[Else
{false part;}]
Note: it is must, use braces {} for all control statements block
Eg.If ($a>$b)
{print $a, is bigger;}Else
{print $b, is bigger};
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
16/39
16
Control Statements - WhileWhile - statement used to repeat set of statements for the givencondition.
Syntax:
While (condition){ statements;}
Eg.while($a
-
8/2/2019 OSP-II UNIT-5
17/39
17
Control Statements - UntilUntil - statement used to repeat set of statements, if the condition isfalse.
Syntax:
Until (condition){ statements;}
Eg.$a=10;Until ($a >15){print $a; #prints till a reaches value 16$a++;}
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
18/39
18
Control Statements - forfor - statement used to repeat set of statements, until meet thegiven condition.
Syntax:
for($i=1;$i
-
8/2/2019 OSP-II UNIT-5
19/39
19
Control Statements for eachThis statement takes a list of values and assigns them one at a timeto a scalar variable, executing a block of code with each successiveassignment.
Syntax:
foreach $var(list)
{statement;}
Eg:
Foreach $a (10,20,30,40,50){print $a;} #print 10,20,.
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
20/39
20
Last Next & Redo Statements Last is similar to break statement of C. Whenever you want toquit from a loop you can use this.
To skip the current loop use the next statement. It immediatelyjumps to the next iteration of the loop.
The redo statement helps in repeating the same iteration again.
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
21/39
21
ListList - A list is an ordered collection of scalars.
list name should start with the symbol @.list has the key as numbers. Starts with 0.
An arrayis a variable that contains a list. In Perl, the two terms areoften used as if they are interchangeable. But, to be accurate, thelist is the data, and the array is the variable.
($f, $b, $d) = ("flintstone", "rubble", dad);here $f has flintstone, $b has rubble and $d has dad
Example
@a=(1,2,3,4,5);
@b=(1..5); #same as above ..-range operatorprint @a; #prints all valuesPrint @a[0]; #prints 1st value
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
22/39
22
HashesHash - Hashes are like arrays but instead of having numbers as theirindex they can have any strings as index. It should have the values asa pair (key, value).
List name should start with the symbol %.To get a single value from hash, use $hashname{index}.To get all keys, can use Keys(%hashname)To get all values, can use values(%hashname)
Example%a=(name,John,age, 23);print %a; #output - nameJohnage23print $a{name}; # prints JohnPrint keys are, keys(%a); # returns nameage
Print values are,values(%a);#returns John23
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
23/39
23
Functions of ListPush and Pop - used to add and remove an element of a listrespectively. Push and pop treat the list variable as a stack andoperate on it. They act on the higher subscript.
Syntax: push(list, value)pop(list)
Example@a=(1,2,3,4,5);Print @a; #prints allPush(@a,12);Print @a;#prints 1,2,3,4,5,12Pop(@a); #removes 12
Print @a; # prints 1,2,3,4,5
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
24/39
24
Functions of ListUnshift and Shift - used to add and remove an element of a listrespectively. They act on the lower subscript.
Syntax: unshift(@list, value)shift(@list)
Example@a=(1,2,3,4,5);Print @a; #prints allunshift(@a,12);Print @a;#prints 12,1,2,3,4,5shift(@a); #removes 12Print @a; # prints 1,2,3,4,5
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
25/39
25
User Defined FunctionsFunction Declaration: The keyword sub describes thefunction. So the function should start with the keyword sub.
It should be preferably either in the end or in the beginningof the main program to improve readability and also ease indebugging.
E.g.:sub function_name(){ coding }
Function Calling: The symbol & should precede the function name
in any function call.E.g. $v1 = &function_name()
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
26/39
26
User Defined FunctionsParameter Passing: Parameter can be passed to the function as a
list . The parameter is taken as a list which is denoted by @_inside
the function. The parameter can be accessed as $_
If only one parameter is passed, the size of @_ list will only be
one.
If two parameters has passed then the @_ size will be two and
the two parameters can be accessed by $_[0],$_[1] ....
More about Parameters & Variables: The variables declared in the main program are by default global
so they will continue to have their values in the function also.
Local variables are declared by putting 'my' while declaring thevariable.
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
27/39
27
User Defined FunctionsReturning Values: Return statement used to return a value to the
called program. If no return statement in a function, the result ofthe last operation is returned.
sub fact()
{My $f=1; #local to functionfor ($i=1; $i
-
8/2/2019 OSP-II UNIT-5
28/39
28
FilesFile Handle: To read and write to files, should create something
called handles which refer to the files.To create the handles, use the OPEN command as follows:
OPEN(filehandleName,filenamewithmode);
E.g.:open(INFILE,"myfile.txt") - reading mode
open(OUTFILE,">myfile.txt") - writing mode indicated by thesymbol >.
open(OUTFILE,">>myfile.txt")- appending mode indicated by thesymbol >>.
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
29/39
29
Files - Reading & WritingReading from a File:
$linevalue = ; #reads a line1. The symbol used to read a line from a file pointed by the filehandle1
and that the line is stored in the scalar variable $linevalue.
2. read function is used to read a specific length of information from afile.read(filehandle,$scalarvariable,length)
Writing into a File:print statement is used to write the content into a file.
print filehandle1 $a,$b
Close a File:
Like PHP, close() function used to close a file.close(filehandle)
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
30/39
30
Files
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
Sample Programs
Read File#!/usr/bin/perlopen (fh, "str.pl");$a = ;print $a; #prints the first line$a = ;
print $a; #prints the second line# Reads all line@a = ; #reads all linesprint @a;
#Reads line by line
while($a = ){print $a;}Close(fh);
Write File:#!/usr/bin/perlopen (infile, ">str1.txt");
print "please enter your name";$name = ;print "please enter your id";$id=;#writes data into the file str1.txtprint infile $id, $name;close(infile);
-
8/2/2019 OSP-II UNIT-5
31/39
31
Files
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
Sample Programs
Append File
#!/usr/bin/perlopen (infile, ">>str1.txt");#opens in append modeprint "please enter your name";$name = ;print "please enter your id";$id=;print infile $id, $name;close(infile);
-
8/2/2019 OSP-II UNIT-5
32/39
32
Pattern Matching
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
* - zero or more times+ - one or more times? - zero or one time^ - beginning of string
$ - end of string. - any character[a-f] - characters a to f[^a-f] - all charactersexcept a to f
{p,q} - at least p times
and at most q times{p,} - at least p times{p} - exactly p times
preg() - used for pattern matching.
Meta characters used for pattern matching:
\b - word boundaries\d - digits\n - newline\r - carriage return\s - white space characters\t - tab\w - alphanumeric characters
-
8/2/2019 OSP-II UNIT-5
33/39
33
Introduction to TCL/TK
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
1. Tcl (originally from "Tool Command Language", but conventionallyrendered as "Tcl" rather than "TCL"; pronounced as "tickle" or "tee-see-ell) is a scripting language created by John Ousterhout.
2. Originally "born out of frustration", according to the author, withprogrammers devising their own (poor quality) languages intended to beembedded into applications, Tcl gained acceptance on its own.
3. It is commonly used for rapid prototyping, scripted applications, GUIs
and testing.4. Tcl is used on embedded systems platforms, both in its full form and in
several other small-footprinted versions.
5. Tcl is also used for CGI scripting and as the scripting language for theEggdrop bot. Tcl is popularly used today in many automated testharnesses, both for software and hardware, and has a loyal following inthe Network Testing and SQA communities.
6. The combination of Tcl and the Tk GUI toolkit is referred to as Tcl/Tk.
-
8/2/2019 OSP-II UNIT-5
34/39
34
Features of TCL/TK
Open Source ProgrammingAuthor: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
1. All operations are commands, including language structures. They arewritten in prefix notation.
2. Commands are commonly variadic.
3. Everything can be dynamically redefined and overridden.
4. All data types can be manipulated as strings, including source code.
5. Event-driven interface to sockets and files. Time-based and user-defined events are also possible.
6. Variable visibility restricted to lexical (static) scope by default, but
uplevel and upvar allowing procs to interact with the enclosing
functions' scopes.
-
8/2/2019 OSP-II UNIT-5
35/39
35
7. All commands defined by Tcl itself generate error messages on
incorrect usage.
8. Extensibility, via C, C++, Java, and Tcl.
9. Interpreted language using bytecode10. Full Unicode (3.1) support, first released 1999.
11. Cross-platform: Windows API; Unix, Linux, Macintosh, etc.
12. Close integration with windowing (GUI) interface Tk.
13. Multiple distribution mechanisms exist.
Features of TCL/TK
Open Source ProgrammingAuthor: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
36/39
36
Introduction to Python
Open Source ProgrammingAuthor: Prof. A. Vi a arani, Asst. Prof., SITE, VIT
Python is an interpreted, general-purpose high-level programminglanguage whose design philosophy emphasizes code readability.
Python aims to combine "remarkable power with very clear syntax",and its standard library is large and comprehensive.
Its use of indentation for block delimiters is unique among popular
programming languages.
-
8/2/2019 OSP-II UNIT-5
37/39
37
Features of Python
Open Source ProgrammingAuthor: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
1. Python is a simple and minimalistic language.2. Python is extremely easy to get started with. Python has an
extraordinarily simple syntax .
3. Python is a Free and Open Source
4. Python is a High-level Language
5. Due to its open-source nature, Python has been ported to manyplatforms
6. Python is interpreted, object oriented and embeddable.
-
8/2/2019 OSP-II UNIT-5
38/39
38
7. Python is extensible If you need a critical piece of code to runvery fast or want to have some piece of algorithm not to be open,
you can code that part of your program in C or C++ and then usethem from your Python program.
8. Python has extensive libraries. i.e. gives support to do regular
expressions, documentation generation, unit testing, threading,databases, web browsers, CGI, ftp, email, XML, XML-RPC, HTML,WAV files, cryptography, GUI (graphical user interfaces), Tk,
Features of Python
Open Source ProgrammingAuthor: Prof. A. Vijayarani, Asst. Prof., SITE, VIT
-
8/2/2019 OSP-II UNIT-5
39/39
39pen Source ProgrammingAuthor: Prof. A. Vijayarani, Asst. Prof., SITE, VIT