Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
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
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
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.
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
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
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.
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
Operations on Strings
1. Concatenation operation . Dot used to concatenate two strings $name1 = VIT; $name2 =University; $name = $name1 . $name2; Print $name; # output VIT University
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
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.
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;
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.
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};
15
16
17
18
19
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
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
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
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
24
25
26
sub add() { my $sum; $sum = $_[0]+$_[1]; #to be returned } $result=&add(5,12); print $result; #prints 17
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 >>.
28
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);
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);
31
Pattern Matching
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
{p,q} - at least p times and at most q times {p,} - at least p times {p} - exactly p times
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.
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.
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.
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.
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.
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.
38
39