Sei sulla pagina 1di 39

Open Source Programming

By Prof. A. Vijayarani SITE VIT

Unit V
Introduction to PERL, TCL & PYTHON
Numbers and Strings Control Statements Lists and Arrays Files Pattern matching Hashes Functions. Introduction to TCL/TK, Introduction to Python.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

Introduction to PERL
What 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 Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

Basic Syntax
Statements 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 Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

Scalars
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 addition or concatenate), generally yielding a scalar result. Scalar variable used to store scalar value. It is a case sensitive. It has to start with the symbol $. Scalars can be read from files and devices, and can be written out as well.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

Scalars - Numbers
Perl provides different format of numbers like integer, decimal, non-decimal integer (hexadecimal, binary & Octal). Though Perl provides different format, it computes with double precision point values. Sample valid data:
1.25 - decimal 255.000 - decimal 255.0 - decimal 7.25e45 - decimal 1234 - integer -40 - integer o377 - Octal ox2AB3 - Hexadecimal ob1011 - Binary

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

Scalars - Strings

Strings are sequences of characters (like hello). Strings may contain 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: Hello 12 th avenue

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

Operations on Numbers
Arithmetic operations + -> addition - -> subtraction * -> multiplication /-> division Relational Operations < -> less than > -> greater than == -> equal to <= -> less than or equal to Logical Operators
&& - and || - or ! - not

%-> modulo division >= -> greater than or equal to ** -> exponent != -> not equal to <=> -> compare, return 1, 0, -1
Short hand assignment operators are available in PERL.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

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 Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

Operations on Strings

1. Concatenation operation . Dot used to concatenate two strings $name1 = VIT; $name2 =University; $name = $name1 . $name2; Print $name; # output VIT University

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

10

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 Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

11

Operations on Strings

3. Pattern Matching & Replace - Perl provides to match a substring 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 substring s used to substitute a substirng g Global match or substitute i for case insensitive.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

12

Operations on Strings
Example $string = "abc123ddDef"; $string =~ s/123/456; # replaces 123 with 456 Print $string; # abc456ddDef $string =~ s/456//; # replaces 456 Print $string; # abcddDef $string=~s/d/s; # replaces 1st character print $string; # abcsdDef $string=~s/d/s/g; #replaces all d print $string; # abcssDef $string =~s/d/s/gi; #replaces all d and D print $string; # abcsssef if ($string =~m/b/) print string contains b; else print string does not have b;

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

13

I/O Statements
Input: Reading from the standard input stream can be done by <>. Evaluating this operator in a scalar context gives the next line of input. Example: Print Enter your name; $name = <>; #gets input from console chomp($name); #removes \n in $name Output: The print operator takes a list of values and sends each item (as a string, of course) to standard output or to files.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

14

Control Statements - IF
If- statement used to take decision and branches the control based on 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 Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

15

Control Statements - While


While - statement used to repeat set of statements for the given condition. Syntax: While (condition) { statements;}

Eg. while($a <10) { print $a; $a++; }

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

16

Control Statements - Until


Until - statement used to repeat set of statements, if the condition is false. Syntax: Until (condition) { statements;} Eg. $a=10; Until ($a >15) { print $a; #prints till a reaches value 16 $a++; }

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

17

Control Statements - for


for - statement used to repeat set of statements, until meet the given condition. Syntax: for($i=1;$i<=10;$i++) { statements;} Eg. for($a=1;$a<=10;$a++) { print $a; #prints till a reaches value 11 $a++; }

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

18

Control Statements for each


This statement takes a list of values and assigns them one at a time to a scalar variable, executing a block of code with each successive assignment. Syntax: foreach $var(list) {statement;} Eg: Foreach $a (10,20,30,40,50) {print $a;} #print 10,20,.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

19

Last Next & Redo Statements


Last is similar to break statement of C. Whenever you want to quit from a loop you can use this. To skip the current loop use the next statement. It immediately jumps to the next iteration of the loop. The redo statement helps in repeating the same iteration again.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

20

List
List - 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 array is a variable that contains a list. In Perl, the two terms are often used as if they are interchangeable. But, to be accurate, the list 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 operator print @a; #prints all values Print @a[0]; #prints 1st value

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

21

Hashes
Hash - Hashes are like arrays but instead of having numbers as their index they can have any strings as index. It should have the values as a 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 - nameJohnage23 print $a{name}; # prints John Print keys are, keys(%a); # returns nameage Print values are,values(%a);#returns John23

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

22

Functions of List
Push and Pop - used to add and remove an element of a list respectively. Push and pop treat the list variable as a stack and operate on it. They act on the higher subscript. Syntax: push(list, value) pop(list) Example @a=(1,2,3,4,5); Print @a; #prints all Push(@a,12); Print @a;#prints 1,2,3,4,5,12 Pop(@a); #removes 12 Print @a; # prints 1,2,3,4,5

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

23

Functions of List
Unshift and Shift - used to add and remove an element of a list respectively. They act on the lower subscript. Syntax: unshift(@list, value) shift(@list) Example @a=(1,2,3,4,5); Print @a; #prints all unshift(@a,12); Print @a;#prints 12,1,2,3,4,5 shift(@a); #removes 12 Print @a; # prints 1,2,3,4,5

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

24

User Defined Functions


Function Declaration: The keyword sub describes the function. So the function should start with the keyword sub. It should be preferably either in the end or in the beginning of the main program to improve readability and also ease in debugging. 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 Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

25

User Defined Functions


Parameter 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 the variable.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

26

User Defined Functions


Returning Values: Return statement used to return a value to the
called program. If no return statement in a function, the result of the last operation is returned. Sample function programs sub fact() { My $f=1; #local to function for ($i=1; $i<=$_[0]; $i++) { $f = $f * $i;} return $f; } $result=&fact(5); print $result; #prints 120

sub add() { my $sum; $sum = $_[0]+$_[1]; #to be returned } $result=&add(5,12); print $result; #prints 17

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

27

Files
File 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 the symbol >. open(OUTFILE,">>myfile.txt")- appending mode indicated by the symbol >>.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

28

Files - Reading & Writing


Reading from a File:
$linevalue = <filehandle1> ; #reads a line 1. 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 a file. 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 Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

29

Files
Sample Programs
Read File #!/usr/bin/perl open (fh, "str.pl"); $a = <fh>; print $a; #prints the first line $a = <fh>; print $a; #prints the second line # Reads all line @a = <fh>; #reads all lines print @a; #Reads line by line while($a = <fh>) {print $a;} Close(fh);

Write File: #!/usr/bin/perl open (infile, ">str1.txt"); print "please enter your name"; $name = <>; print "please enter your id"; $id=<>; #writes data into the file str1.txt print infile $id, $name; close(infile);

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

30

Files
Sample Programs
Append File #!/usr/bin/perl open (infile, ">>str1.txt");#opens in append mode print "please enter your name"; $name = <>; print "please enter your id"; $id=<>; print infile $id, $name; close(infile);

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

31

Pattern Matching
preg() - used for pattern matching. Meta characters used for pattern matching:

* - 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 characters except a to f

\b - word boundaries \d - digits \n - newline \r - carriage return \s - white space characters \t - tab \w - alphanumeric characters

{p,q} - at least p times and at most q times {p,} - at least p times {p} - exactly p times

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

32

Introduction to TCL/TK
1. Tcl (originally from "Tool Command Language", but conventionally rendered as "Tcl" rather than "TCL"; pronounced as "tickle" or "teesee-ell) is a scripting language created by John Ousterhout. 2. Originally "born out of frustration", according to the author, with programmers devising their own (poor quality) languages intended to be embedded 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 the Eggdrop bot. Tcl is popularly used today in many automated test harnesses, both for software and hardware, and has a loyal following in the Network Testing and SQA communities. 6. The combination of Tcl and the Tk GUI toolkit is referred to as Tcl/Tk.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

33

Features of TCL/TK
1. All operations are commands, including language structures. They are written 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 userdefined 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.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

34

Features of TCL/TK

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 bytecode 10. 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.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

35

Introduction to Python
Python is an interpreted, general-purpose high-level programming language 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.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

36

Features of Python
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 many platforms 6. Python is interpreted, object oriented and embeddable.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

37

Features of Python
7. Python is extensible If you need a critical piece of code to run very 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 use them from your Python program. 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,

8.

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

38

Open Source Programming


Author: Prof. A. Vijayarani, Asst. Prof., SITE, VIT

39

Potrebbero piacerti anche