Introduction to Scripting Languages and Perl Basics

23
1 Introduction to Scripting Introduction to Scripting Languages and Perl Basics Languages and Perl Basics CSCI 431 Programming Languages CSCI 431 Programming Languages Fall 2003 Fall 2003 A modification of slides A modification of slides developed by Felix Hernandez- developed by Felix Hernandez- Campos at UNC Chapel Hill Campos at UNC Chapel Hill

description

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 - PowerPoint PPT Presentation

Transcript of Introduction to Scripting Languages and Perl Basics

Page 1: Introduction to Scripting Languages and Perl Basics

11

Introduction to Scripting Introduction to Scripting Languages and Perl BasicsLanguages and Perl Basics

CSCI 431 Programming LanguagesCSCI 431 Programming Languages

Fall 2003Fall 2003

A modification of slides developed by Felix A modification of slides developed by Felix Hernandez-Campos at UNC Chapel Hill Hernandez-Campos at UNC Chapel Hill

Page 2: Introduction to Scripting Languages and Perl Basics

22

Origin of Scripting LanguagesOrigin of Scripting Languages

• Scripting languages originated as Scripting languages originated as job control job control languageslanguages

– 1960s: IBM System 360 had the Job Control Language1960s: IBM System 360 had the Job Control Language– ScriptsScripts used to control other programs used to control other programs

» Launch compilation, executionLaunch compilation, execution» Check return codesCheck return codes

• Scripting languages got increasingly more powerful Scripting languages got increasingly more powerful in the UNIX world in the early 1970’sin the UNIX world in the early 1970’s

– Shell programming (sh, csh, ksh), AWK, SED, GREPShell programming (sh, csh, ksh), AWK, SED, GREP– ScriptsScripts used to combine used to combine componentscomponents

» GluingGluing applications [Ousterhout, 97] applications [Ousterhout, 97]

Page 3: Introduction to Scripting Languages and Perl Basics

33

High-Level Programming LanguagesHigh-Level Programming Languages

• High-level programming languages replaced High-level programming languages replaced assembly languagesassembly languages

– Benefits:Benefits:» The compiler hides unnecessary details, so these languages have a The compiler hides unnecessary details, so these languages have a

higher level of abstraction, increasing productivityhigher level of abstraction, increasing productivity» They are They are strongly typedstrongly typed, , i.e. i.e. meaning of information is specified meaning of information is specified

before its use, enabling substantial error checking at compile timebefore its use, enabling substantial error checking at compile time» They make programs more portableThey make programs more portable

– HLPLs and ALs are both intended to write application HLPLs and ALs are both intended to write application from scratchfrom scratch

– HLLs try to minimize the loss in performance with respect HLLs try to minimize the loss in performance with respect to ALsto ALs

– E.g.E.g. PL/1, Pascal, C, C++, Java PL/1, Pascal, C, C++, Java

Page 4: Introduction to Scripting Languages and Perl Basics

44

Higher-level ProgrammingHigher-level Programming

• Scripting languages provide an even higher-level of Scripting languages provide an even higher-level of abstractionabstraction

– The main goal is programming productivityThe main goal is programming productivity» Performance is a secondary considerationPerformance is a secondary consideration

– Modern SL provide primitive operations with greater Modern SL provide primitive operations with greater functionalityfunctionality

• Scripting languages are usually (almost always) Scripting languages are usually (almost always) interpretedinterpreted

– Interpretation increases speed of developmentInterpretation increases speed of development» Immediate feedbackImmediate feedback

– Compilation to an intermediate format is commonCompilation to an intermediate format is common

Page 5: Introduction to Scripting Languages and Perl Basics

55

Higher-level ProgrammingHigher-level Programming

• They are They are weakly typedweakly typed– I.e. I.e. Meaning of information is inferredMeaning of information is inferredLess error checking at compile-time Less error checking at compile-time

» Run-time error checking is less efficient, but possibleRun-time error checking is less efficient, but possibleWeak typing increases speed of developmentWeak typing increases speed of development

» More flexible interfacingMore flexible interfacing» Fewer lines of codeFewer lines of code

• They are not usually appropriate forThey are not usually appropriate for– Efficient/low-level programmingEfficient/low-level programming– Large programsLarge programs

Page 6: Introduction to Scripting Languages and Perl Basics

66

Typing and ProductivityTyping and Productivity

[Ousterhout, 97][Ousterhout, 97]

Page 7: Introduction to Scripting Languages and Perl Basics

77

PerlPerl

• Perl was written by Larry Wall in 1986. Perl was written by Larry Wall in 1986. – He continues to develop and maintain the languageHe continues to develop and maintain the language– It is available on virtually every computer platform, from It is available on virtually every computer platform, from

Apple Macintosh to VMS. Apple Macintosh to VMS.

• Perl is an acronym for: Perl is an acronym for: – "Practical Extraction and Report Language""Practical Extraction and Report Language"– or, jokingly, "Pathologically Eclectic Rubbish Lister" or, jokingly, "Pathologically Eclectic Rubbish Lister" – It started out as a scripting language to supplement It started out as a scripting language to supplement rnrn, the , the

ubiquitous USENET reader, which Wall also wrote.ubiquitous USENET reader, which Wall also wrote.

• It is an interpreted language that is optimized for It is an interpreted language that is optimized for string manipulation, I/O, and system tasks. string manipulation, I/O, and system tasks.

Page 8: Introduction to Scripting Languages and Perl Basics

88

CharacteristicsCharacteristics

• Occupies the middle ground between a compiled Occupies the middle ground between a compiled language and a traditional interpreted languagelanguage and a traditional interpreted language

Perl scriptPerl script

Perl reads entire scriptPerl reads entire script

Converts to compact intermediate formConverts to compact intermediate form(a tree structure)(a tree structure)

ExecutesExecutes

Page 9: Introduction to Scripting Languages and Perl Basics

99

Perl can be simplePerl can be simple

Perl can make simple programs much Perl can make simple programs much shorter, and easier to write. shorter, and easier to write.

C codeC code Perl codePerl code #include <stdio.h> #include <stdio.h> print "Hello World\n"; print "Hello World\n"; main() { main() { printf("Hello World\n"); printf("Hello World\n"); } }

Comments are proceeded by the # character, Comments are proceeded by the # character, and and continue until the end of the line. Statements continue until the end of the line. Statements end end in a semi-colon.in a semi-colon.

$J = 333; # assigns the value 33 to the $J = 333; # assigns the value 33 to the scalar J scalar J

Page 10: Introduction to Scripting Languages and Perl Basics

1010

Running a Perl programRunning a Perl program

• You can run a script explicitly with perl (the % is your You can run a script explicitly with perl (the % is your command prompt) command prompt) % perl scriptname % perl scriptname or or % cat scriptname | perl % cat scriptname | perl

• UNIX shells have a shortcut. If a text file is executable, UNIX shells have a shortcut. If a text file is executable, and the first line is of the form: 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] program [optional program arguments]

scriptname scriptname ExampleExample Add the first line: Add the first line: #!/usr/local/bin/perl #!/usr/local/bin/perl (or (or

whatever the location of your perl binary is), save, exit whatever the location of your perl binary is), save, exit the editor, and make the program executable: the editor, and make the program executable:

Page 11: Introduction to Scripting Languages and Perl Basics

1111

Data TypesData 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.

Page 12: Introduction to Scripting Languages and Perl Basics

1212

Scalar TypesScalar Types• Scalars can hold numbers, booleans, references (to be covered Scalars can hold numbers, booleans, references (to be covered

later), and stringslater), and strings– These values are interchangeable. These values are interchangeable. – All scalar variables are proceeded by the All scalar variables are proceeded by the $$ character. character.

• NumbersNumbers are represented as either integers, or double are represented as either integers, or double precision floating point numbers, depending on context. precision floating point numbers, depending on context.

– examples: examples: $a = 4; $A=5; $count = 0; $_= 5.3333;$a = 4; $A=5; $count = 0; $_= 5.3333;

• StringsStrings are usually delimited by single or double quotes. are usually delimited by single or double quotes. – Double quote delimited strings are subject to backslash and variable Double quote delimited strings are subject to backslash and variable

interpolation; single quote delimited strings are not. interpolation; single quote delimited strings are not. – The most common backslashed characters are \n for a newline, and \t The most common backslashed characters are \n for a newline, and \t

for a tab (look familiar?). for a tab (look familiar?). – examples: examples: $a = "hello"; $a = join(“ “, @array);$a = "hello"; $a = join(“ “, @array);

Page 13: Introduction to Scripting Languages and Perl Basics

1313

Comparing strings and Comparing strings and numbers numbers

FunctionFunction StringsStrings NumericsNumerics equal equal eq eq == == not equal not equal ne ne != != less than less than lt lt < < greater then greater then gt gt > > less than or equal to less than or equal to le le <= <= greater than or equal to greater than or equal to ge ge >= >= comparison with signed comparison with signed cmp cmp <=> <=>

Page 14: Introduction to Scripting Languages and Perl Basics

1414

ContextContext

• Many operators in Perl operate on all 3 kinds of basic Many operators in Perl operate on all 3 kinds of basic data.data.

• Polymorphism in Perl is known as Polymorphism in Perl is known as contextcontext. The . The context of the variable determines it’s type and the context of the variable determines it’s type and the behavior of the operator involved.behavior of the operator involved.

• Example:Example:$v1 = 127;$v1 = 127;$v1 += “ and more!!”;$v1 += “ and more!!”;print $v1; print $v1; 127 and more!! 127 and more!! (displays)(displays)

Page 15: Introduction to Scripting Languages and Perl Basics

1515

ContextContext

• Any legal variable name can be used to designate a Any legal variable name can be used to designate a scalarscalar, an , an arrayarray, or an , or an associative arrayassociative array (a.k.a. a (a.k.a. a hashhash))

• The leading character determines which is being The leading character determines which is being usedused

– Example: Example: $name$name @name@name %name%name

• The interpreter supplies appropriate initial valuesThe interpreter supplies appropriate initial values

Page 16: Introduction to Scripting Languages and Perl Basics

1616

ArraysArrays

• ArraysArrays are ordered groups of variables. are ordered groups of variables. • They are always proceeded by the They are always proceeded by the @@ character. character. • Arrays are composed of comma separated values Arrays are composed of comma separated values

surrounded by parenthesis. surrounded by parenthesis. • Examples:Examples:

@teachers = ("Vose", "Berry", "Vander @teachers = ("Vose", "Berry", "Vander Zanden"); Zanden");

@letters = @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); (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); @percentages = (33.5555,55.0,11); @teachers = @letters;@teachers = @letters;($a, $b, $c) = @percentages;($a, $b, $c) = @percentages;@a=split(“ “, $my_string);@a=split(“ “, $my_string);

Page 17: Introduction to Scripting Languages and Perl Basics

1717

ArraysArrays

• Array values are accessed via the $ operator and identified by Array values are accessed via the $ operator and identified by an integer value surrounded by brackets [ ]. an integer value surrounded by brackets [ ].

• As in the C programming language, Arrays indices always As in the C programming language, Arrays indices always begin at 0. begin at 0.

• To access the letter To access the letter cc in the array in the array @letters@letters (on the previous (on the previous slide) you would refer to slide) you would refer to $letters[2], @array=@letters[1,2];$letters[2], @array=@letters[1,2];

• To determine the number of elements in an array, you assign To determine the number of elements in an array, you assign the array to a scalar value as seen below: the array to a scalar value as seen below: $count = @letters;$count = @letters;

• The scalar count receives a value equal to the number of The scalar count receives a value equal to the number of elements in the array letters. elements in the array letters.

Page 18: Introduction to Scripting Languages and Perl Basics

1818

ArraysArrays

• Perl provides built-in functions which operate on Perl provides built-in functions which operate on arrays, treating them as stacks or queues.arrays, treating them as stacks or queues.

Direct MethodDirect Method Splice Equiv.Splice Equiv.push(@a, $x)push(@a, $x) splice(@a, $#a+1, 0, $x)splice(@a, $#a+1, 0, $x)$b=pop(@a)$b=pop(@a) $b=splice(@a, $#a,1)$b=splice(@a, $#a,1)$b=shift(@a)$b=shift(@a) $b=splice(@a, 0, 1)$b=splice(@a, 0, 1)unshift(@a, $x)unshift(@a, $x) splice(@a, 0, 0, $x)splice(@a, 0, 0, $x)

Page 19: Introduction to Scripting Languages and Perl Basics

1919

HashsHashs

• HashesHashes are unordered sets of key/value pairs. They are always are unordered sets of key/value pairs. They are always proceeded by the proceeded by the %% character. character.

• Values are assigned with the key with either a comma Values are assigned with the key with either a comma ,, or an arrow or an arrow =>=> . Entire hash assignments surrounded by parenthesis. . Entire hash assignments surrounded by parenthesis. Examples: Examples: %grades = ('Mackey',A , “Frost”,B, 'Jhonston',C , %grades = ('Mackey',A , “Frost”,B, 'Jhonston',C ,

'Toms',A); 'Toms',A); %jersey_numbers = (Ripken => 8, Hayes => 22, Ruth %jersey_numbers = (Ripken => 8, Hayes => 22, Ruth

=> 3);=> 3); • One way to access a value from its key is shown belowOne way to access a value from its key is shown below: :

$number = $jersey_numbers{"Ripken"}; $number = $jersey_numbers{"Ripken"}; # $number = 8 # $number = 8(Note that subscripts are delimited with curly brackets)(Note that subscripts are delimited with curly brackets)$wife{“tom”}=[“sue”, “sally”, “jane”];$wife{“tom”}=[“sue”, “sally”, “jane”];$secondWife = $wife{“tom”}[1];$secondWife = $wife{“tom”}[1];

Page 20: Introduction to Scripting Languages and Perl Basics

2020

I/O with PerlI/O with Perl

• Perl uses Perl uses filehandlesfilehandles to control input and to control input and output.output.

• Perl has 3 built-in filehandles which are opened Perl has 3 built-in filehandles which are opened automatically for each program:automatically for each program:– STDIN, STDOUT, and STDERR. STDIN, STDOUT, and STDERR.

• Additional filehandles are created by the Additional filehandles are created by the openopen command. command. open(DATA, "myfile.text"); open(DATA, "myfile.text"); # opens myfile.text for reading # opens myfile.text for reading # with the filehandle DATA # with the filehandle DATA

open(OUT,">myfile.text");open(OUT,">myfile.text"); # opens myfile.text for writing # opens myfile.text for writing # with the filehandle OUT # with the filehandle OUT

open(OUT2,">>myfile.text");open(OUT2,">>myfile.text"); # opens myfile.text for # opens myfile.text for appending appending

# with the filehandle OUT2 # with the filehandle OUT2

Page 21: Introduction to Scripting Languages and Perl Basics

2121

Perl I/OPerl I/O

• Open returns a Open returns a truetrue if the file is if the file is successfully opened, and successfully opened, and falsefalse on failure. on failure.

• To access files, surround the filehandle To access files, surround the filehandle with the with the diamond operatordiamond operator: <DATA> : <DATA>

open(INPUT,"input1.txt"); open(INPUT,"input1.txt"); while($line = <INPUT>) {while($line = <INPUT>) {

print $line;print $line;} }

Page 22: Introduction to Scripting Languages and Perl Basics

2222

Perl I/OPerl I/O

• Perl provides the Perl provides the closeclose command to command to deallocate filehandles as seen below: deallocate filehandles as seen below: close(OUT2);close(OUT2); # closes filehandle OUT2 # closes filehandle OUT2

• Example:Example:open(INPUT,"input1.txt"); open(INPUT,"input1.txt"); while(<INPUT>) {while(<INPUT>) {

print $_;print $_;} } close(INPUT); close(INPUT);

Page 23: Introduction to Scripting Languages and Perl Basics

2323

Reading AssignmentReading Assignment

• John K. Ousterhout, John K. Ousterhout, Scripting: Higher-Level Scripting: Higher-Level Programming for the 21Programming for the 21stst Century Century, 1997, 1997

– http://home.pacbell.net/ouster/scripting.htmlhttp://home.pacbell.net/ouster/scripting.html

• Perl TutorialPerl Tutorial– http://archive.http://archive.ncsancsa..uiucuiuc..eduedu/General/Training//General/Training/PerlIntroPerlIntro