240 likes | 425 Views
Introduction to Scripting Languages and Perl Basics. CSCI 431 Programming Languages Fall 2003. A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill . Origin of Scripting Languages. Scripting languages originated as job control languages
E N D
Introduction to Scripting Languages and Perl Basics CSCI 431 Programming Languages Fall 2003 A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill
Origin of Scripting Languages • Scripting languages originated as job control languages • 1960s: IBM System 360 had the Job Control Language • Scripts used to control other programs • Launch compilation, execution • Check return codes • Scripting languages got increasingly more powerful in the UNIX world in the early 1970’s • Shell programming (sh, csh, ksh), AWK, SED, GREP • Scripts used to combine components • Gluing applications [Ousterhout, 97]
High-Level Programming Languages • High-level programming languages replaced assembly languages • Benefits: • The compiler hides unnecessary details, so these languages have a higher level of abstraction, increasing productivity • They are strongly typed, i.e. meaning of information is specified before its use, enabling substantial error checking at compile time • They make programs more portable • HLPLs and ALs are both intended to write application from scratch • HLLs try to minimize the loss in performance with respect to ALs • E.g. PL/1, Pascal, C, C++, Java
Higher-level Programming • Scripting languages provide an even higher-level of abstraction • The main goal is programming productivity • Performance is a secondary consideration • Modern SL provide primitive operations with greater functionality • Scripting languages are usually (almost always) interpreted • Interpretation increases speed of development • Immediate feedback • Compilation to an intermediate format is common
Higher-level Programming • They are weakly typed • I.e. Meaning of information is inferred • Less error checking at compile-time • Run-time error checking is less efficient, but possible • Weak typing increases speed of development • More flexible interfacing • Fewer lines of code • They are not usually appropriate for • Efficient/low-level programming • Large programs
Typing and Productivity [Ousterhout, 97]
Perl • Perl was written by Larry Wall in 1986. • He continues to develop and maintain the language • It is available on virtually every computer platform, from Apple Macintosh to VMS. • Perl is an acronym for: • "Practical Extraction and Report Language" • or, jokingly, "Pathologically Eclectic Rubbish Lister" • It started out as a scripting language to supplement rn, the ubiquitous USENET reader, which Wall also wrote. • It is an interpreted language that is optimized for string manipulation, I/O, and system tasks.
Characteristics • Occupies the middle ground between a compiled language and a traditional interpreted language Perl script Perl reads entire script Converts to compact intermediate form (a tree structure) Executes
Perl can be simple Perl can make simple programs much shorter, and easier to write. C codePerl code #include <stdio.h> print "Hello World\n"; main() { printf("Hello World\n"); } Comments are proceeded by the # character, and continue until the end of the line. Statements end in a semi-colon. $J = 333; # assigns the value 33 to the scalar J
Running a Perl program • You can run a script explicitly with perl (the % is your command prompt) % perl scriptname or % cat scriptname | perl • UNIX shells have a shortcut. If a text file is executable, and the first line is of the form: #!program [optional program arguments] the shell executes program [optional program arguments] scriptname Example Add the first line: #!/usr/local/bin/perl (or whatever the location of your perl binary is), save, exit the editor, and make the program executable:
Data Types • Scalars:contains a single value • Arrays:an ordered list of scalars accessed by the scalar’s position in the list • Associative arrays (hashes): an unordered set of scalars accessed by some string value that is associated with each scalar Perl variables do not need to be declared prior to their use. Perl interprets variables based on context. Example – If the value “56” is assigned to a variable, it will be interpreted as an integer in some cases and a string in others.
Scalar Types • Scalars can hold numbers, booleans, references (to be covered later), and strings • These values are interchangeable. • All scalar variables are proceeded by the $ character. • Numbers are represented as either integers, or double precision floating point numbers, depending on context. • examples: $a = 4; $A=5; $count = 0; $_= 5.3333; • Strings are usually delimited by single or double quotes. • Double quote delimited strings are subject to backslash and variable interpolation; single quote delimited strings are not. • The most common backslashed characters are \n for a newline, and \t for a tab (look familiar?). • examples: $a = "hello"; $a = join(“ “, @array);
Comparing strings and numbers FunctionStringsNumerics equal eq == not equal ne != less than lt < greater then gt > less than or equal to le <= greater than or equal to ge >= comparison with signed cmp <=>
Context • Many operators in Perl operate on all 3 kinds of basic data. • Polymorphism in Perl is known as context. The context of the variable determines it’s type and the behavior of the operator involved. • Example: $v1 = 127; $v1 += “ and more!!”; print $v1; 127 and more!! (displays)
Context • Any legal variable name can be used to designate a scalar, an array, or an associative array (a.k.a. a hash) • The leading character determines which is being used • Example: $name @name %name • The interpreter supplies appropriate initial values
Arrays • Arrays are ordered groups of variables. • They are always proceeded by the @ character. • Arrays are composed of comma separated values surrounded by parenthesis. • Examples: @teachers = ("Vose", "Berry", "Vander Zanden"); @letters = (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x); @percentages = (33.5555,55.0,11); @teachers = @letters; ($a, $b, $c) = @percentages; @a=split(“ “, $my_string);
Arrays • Array values are accessed via the $ operator and identified by an integer value surrounded by brackets [ ]. • As in the C programming language, Arrays indices always begin at 0. • To access the letter c in the array @letters (on the previous slide) you would refer to $letters[2], @array=@letters[1,2]; • To determine the number of elements in an array, you assign the array to a scalar value as seen below: $count = @letters; • The scalar count receives a value equal to the number of elements in the array letters.
Arrays • Perl provides built-in functions which operate on arrays, treating them as stacks or queues. Direct MethodSplice Equiv. push(@a, $x) splice(@a, $#a+1, 0, $x) $b=pop(@a) $b=splice(@a, $#a,1) $b=shift(@a) $b=splice(@a, 0, 1) unshift(@a, $x) splice(@a, 0, 0, $x)
Hashs • Hashes are unordered sets of key/value pairs. They are always proceeded by the % character. • Values are assigned with the key with either a comma , or an arrow => . Entire hash assignments surrounded by parenthesis. Examples: %grades = ('Mackey',A , “Frost”,B, 'Jhonston',C , 'Toms',A); %jersey_numbers = (Ripken => 8, Hayes => 22, Ruth => 3); • One way to access a value from its key is shown below: $number = $jersey_numbers{"Ripken"}; # $number = 8 (Note that subscripts are delimited with curly brackets) $wife{“tom”}=[“sue”, “sally”, “jane”]; $secondWife = $wife{“tom”}[1];
I/O with Perl • Perl uses filehandles to control input and output. • Perl has 3 built-in filehandles which are opened automatically for each program: • STDIN, STDOUT, and STDERR. • Additional filehandles are created by the open command. open(DATA, "myfile.text"); # opens myfile.text for reading # with the filehandle DATA open(OUT,">myfile.text"); # opens myfile.text for writing # with the filehandle OUT open(OUT2,">>myfile.text"); # opens myfile.text for appending # with the filehandle OUT2
Perl I/O • Open returns a true if the file is successfully opened, and false on failure. • To access files, surround the filehandle with the diamond operator: <DATA> open(INPUT,"input1.txt"); while($line = <INPUT>) { print $line; }
Perl I/O • Perl provides the close command to deallocate filehandles as seen below: close(OUT2); # closes filehandle OUT2 • Example: open(INPUT,"input1.txt"); while(<INPUT>) { print $_; } close(INPUT);
Reading Assignment • John K. Ousterhout, Scripting: Higher-Level Programming for the 21st Century, 1997 • http://home.pacbell.net/ouster/scripting.html • Perl Tutorial • http://archive.ncsa.uiuc.edu/General/Training/PerlIntro