Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Introduction to Scripting Languages and Perl Basics CSCI 431 Programming Languages Fall 2003 A modification of slides developed by Felix Hernandez-Campos.

Similar presentations


Presentation on theme: "1 Introduction to Scripting Languages and Perl Basics CSCI 431 Programming Languages Fall 2003 A modification of slides developed by Felix Hernandez-Campos."— Presentation transcript:

1 1 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

2 2 Origin of Scripting Languages Scripting languages originated as job control languagesScripting 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’sScripting 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]

3 3 High-Level Programming Languages High-level programming languages replaced assembly languagesHigh-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

4 4 Higher-level Programming Scripting languages provide an even higher-level of abstractionScripting 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) interpretedScripting languages are usually (almost always) interpreted –Interpretation increases speed of development »Immediate feedback –Compilation to an intermediate format is common

5 5 Higher-level Programming They are weakly typedThey 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 Weak typing increases speed of development »More flexible interfacing »Fewer lines of code They are not usually appropriate forThey are not usually appropriate for –Efficient/low-level programming –Large programs

6 6 Typing and Productivity [Ousterhout, 97]

7 7 Perl Perl was written by Larry Wall in 1986.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: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.It is an interpreted language that is optimized for string manipulation, I/O, and system tasks.

8 8 Characteristics Occupies the middle ground between a compiled language and a traditional interpreted languageOccupies 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

9 9 Perl can be simple Perl can make simple programs much shorter, and easier to write. Perl can make simple programs much shorter, and easier to write. C code Perl code #include print "Hello World\n"; main() { printf("Hello World\n"); 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

10 10 Running a Perl program You can run a script explicitly with perl (the % is your command prompt)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:UNIX shells have a shortcut. If a text file is executable, and the first line is of the form: #!program [optional program arguments] #!program [optional program arguments] the shell executes the shell executes program [optional program arguments] scriptname program [optional program arguments] scriptnameExample 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: 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:

11 11 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.

12 12 Scalar Types Scalars can hold numbers, booleans, references (to be covered later), and stringsScalars 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.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.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);

13 13 Comparing strings and numbers Function Strings Numerics 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 comparison with signed cmp

14 14 Context Many operators in Perl operate on all 3 kinds of basic data.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.Polymorphism in Perl is known as context. The context of the variable determines it’s type and the behavior of the operator involved. Example:Example: $v1 = 127; $v1 += “ and more!!”; print $v1;  127 and more!! (displays) (displays)

15 15 Context Any legal variable name can be used to designate a scalar, an array, or an associative array (a.k.a. a hash)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 usedThe leading character determines which is being used –Example: $name@name%name The interpreter supplies appropriate initial valuesThe interpreter supplies appropriate initial values

16 16 Arrays Arrays are ordered groups of variables.Arrays are ordered groups of variables. They are always proceeded by the @ character.They are always proceeded by the @ character. Arrays are composed of comma separated values surrounded by parenthesis.Arrays are composed of comma separated values surrounded by parenthesis. Examples: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);

17 17 Arrays Array values are accessed via the $ operator and identified by an integer value surrounded by brackets [ ].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.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 toTo 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: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.The scalar count receives a value equal to the number of elements in the array letters.

18 18 Arrays Perl provides built-in functions which operate on arrays, treating them as stacks or queues.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)

19 19 Hashs Hashes are unordered sets of key/value pairs. They are always proceeded by the % character.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: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 :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];

20 20 I/O with Perl Perl uses filehandles to control input and output.Perl uses filehandles to control input and output. Perl has 3 built-in filehandles which are opened automatically for each program: 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.Additional filehandles are created by the open command. open(DATA, "myfile.text"); # opens myfile.text for reading 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 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 OUT open(OUT2,">>myfile.text"); # opens myfile.text for appending # with the filehandle OUT2 # with the filehandle OUT2

21 21 Perl I/O Open returns a true if the file is successfully opened, and false on failure.Open returns a true if the file is successfully opened, and false on failure. To access files, surround the filehandle with the diamond operator: To access files, surround the filehandle with the diamond operator: open(INPUT,"input1.txt"); while($line = ) { print $line; }

22 22 Perl I/O Perl provides the close command to deallocate filehandles as seen below:Perl provides the close command to deallocate filehandles as seen below: close(OUT2); # closes filehandle OUT2 Example:Example:open(INPUT,"input1.txt"); while( ) { print $_; }close(INPUT);

23 23 Reading Assignment John K. Ousterhout, Scripting: Higher-Level Programming for the 21 st Century, 1997John K. Ousterhout, Scripting: Higher-Level Programming for the 21 st Century, 1997 –http://home.pacbell.net/ouster/scripting.html http://home.pacbell.net/ouster/scripting.html Perl TutorialPerl Tutorial –http://archive.ncsa.uiuc.edu/General/Training/PerlIntro http://archive.ncsa.uiuc.edu/General/Training/PerlIntro


Download ppt "1 Introduction to Scripting Languages and Perl Basics CSCI 431 Programming Languages Fall 2003 A modification of slides developed by Felix Hernandez-Campos."

Similar presentations


Ads by Google