Scripting Languages CSC 360
Popular in Course
Popular in ComputerScienence
This 7 page Study Guide was uploaded by Micaela Luettgen on Thursday October 15, 2015. The Study Guide belongs to CSC 360 at Murray State University taught by William Lyle in Fall. Since its upload, it has received 38 views. For similar materials see /class/223615/csc-360-murray-state-university in ComputerScienence at Murray State University.
Reviews for Scripting Languages
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 10/15/15
CSC 360 Study Guide Learning Perl 5 Edition Chapter 1 Introduction Excellent overview of Perl and source of Perl resources online See the simple Hello World program print39 is used to produce output and indicates a comment In Perl version 510 you can use 39say39 instead of 39print39 must also include the line 39use 5 010 39 at the beginning of the program Chapter 2 Scalar Data Numbers 7 all numbers are stored as doubles arithmetic operators are for addition subtraction multiplication division modulus and exponentiation respectively Strings 7 sequences of characters enclosed in either single quotes or double quotes backslash escapes eg n or t see Table 21 p 23 24 are interpreted inside double quotes but are treated as standard characters inside single quotes The string concatenation operator is the period 3939 Perl automatically converts numbers to strings and vice versa as required Scalar variables begin with a sign followed by an underscore or letter and then possibly more letters digits and underscores Assignment is accomplished with operator there are also the 2 2 and 2 operators Variable interpolation in strings Double quoted strings that contain a variable name will have the variable replaced by its value See Table 2 2 p 31 32 for operator precedence and associativity The comparison operators are 2 lt lt gt2 and gt for numeric values and eq ne lt le gt and ge for strings The if statement 7if condition statements The line input operator ltSTDINgt is used to get input from the keyboard as a string This typically has a newline character at the end of it that can be removed with the 39chomp39 operator The while loop 7 while condition statements Scalar variables have the special value undef before they are assigned a value This will be used as 0 or an empty string in expressions The de ned function can test a variable for the undef value Chapter 3 Lists and Arrays A list is an ordered collection of scalars An array is a variable that contains a list The individual values can be strings numbers or undef values and need not all be of the same type Subscripts are integers and always begin at 0 Arrays are automatically extended to accommodate previously non existent elements The last subscript of an array named rocks is given by rocks You can remove the tail or extend an array by modifying the value of this variable You may also use negative subscripts to refer to elements from the end of the array List literals contain 0 or more values in parentheses separated by commas but also may contain references to other variables or ranges of values 1 2 5 7 quotlarryquot is the same as l 2 3 4 5 7 quotlarryquot The qw shortcut stands for quoted words or quoted by whitespace so quotLarry quotMoequot Curlyquot is the same as qw Larry Moe Curly The delimiter need not be a 39 39 but could be almost any punctuation character List literals may appear on the right hand side of an assignment and may be used to assign to an array by using the 3939 before the array name stooges qw Larry Moe Curly The push and pop operators allow you to add and remove elements at the end of an array so fred pop array removes the last element from array permanently and assigns it to f red while push array a would put a as the last element of array The shif t and unshif t operators work on the beginning of an array in the same way that push and pop work on the end of the array Entire arrays will be interpolated into quoted strings using array if array qw one two three then quotzero array endquot will be the same as quotzero one two three endquot The foreach loop gives a convenient method to iterate over all the elements in a list or an array The reverse operator takes a list or an array that contains a list and returns the list in reverse order The sort operator likewise returns a list in sorted ASCllbetical order This will probably not give the desired results if the list contains numbers VERY important section on Scalar and List context The name of an array returns a list in a list context and the number of elements in a scalar context Be sure to read and understand this section and all of the examples in it In a scalar context ltSTDINgt returns the next line of input while in a list context ltSTDINgt returns the remainder of all of standard input up to the end of file marker Chapter 4 Subroutines Subroutines are defined by the word sub followed by the name of the subroutine then the block of code in curly braces which makes up the body of the subroutine A subroutine is invoked by preceding its name with the 39amp39 symbol The value of the last expression in the subroutine is the value that is returned The parameters to a subroutine are stored in the local array which can be tested to see how many actual parameters were sent By default all Perl variables are global in scope They can be declared local to a subroutine using the 39my39 operator The return operator can specify a value to be returned instead of the last expression the subroutine A subroutine may be invoked without the preceding 39amp if the compiler can determine that it really is a subroutine call the definition came earlier or the parameters are inside parentheses The 39amp39 is required if your subroutine has the same name as a built in function In perl 510 we may use the state declaration to indicate that a variable should retain its value from one invocation of the subroutine to the next Chapter 5 Input and Output We have seen ltSTDINgt earlier A typical loop to process standard input until end of file might be while definedline ltSTDINgt process line Perl gives a simple shortcut while ltSTDINgt process or in a list context foreach ltSTDINgt process The diamond operator ltgt can be used to process one or more files named on the command line Technically the diamond operator gets the name from the ARGV array ARGV is automatically initialized with the list of command line arguments if any Output can be formatted using printf instead of print This is very similar to prinrf in C and C Filehandles are names for an IO connection between your program and the outside world recommended to be in all caps There are six special filehandle names STDIN STDOUT STDERR DATA ARGV ARGVOUT Input output redirection can be done with lt and gt respectively Output can be piped to another program with Opening afilehandle open CONFIG quotdinoquot is the same as open CONFIG quotltdinoquot both open the file named dino for input through the filehandle CONFIG open BEDROCK quotgtfredquot opens fred for output and open LOG gtgtlogf ilequot appends output to the end of existing file logfile Closing afilehandle close BEDROCK Bad Filehandles record the status of opens with my success open LOG gtgtlogfilequot Now you can test success to see if the open was successful or not A better way is to use die Fatal Errors with die Consider the code if I open LOG gtgtlogfilequot die quotCannot create logfile 1quot This attempts to open the filehandle if it fails your program tenninates giving the message Cannot as well as the error mes sage from the operating system stored in the variable l Warning messages you can use warn just like die to issue warning messages but program is not tenninated Using Filehandles to read from the file etcpasswd if I open PASSWD quotetcpasswdquot die quotOh Crap 1 quot7 while ltPASSWDgt process each line To write to a file opened for output using either print or print print LOG whatever quot printf STDERR quotgad percent complete nquot donetotal 100 You can use the select statement to change the default output filehandle Setting the special variable l forces the output buffer to be ushed after each output operation The say keyword is similar to print but it adds a newline Chapter 6 Hashes A hash is similar to an array except that the subscripts called keys are strings instead of integers but must be unique Individual values in a hash are accessed by enclosing the key value in curly braces similar to square brackets and integer subscripts for arrays To refer to the entire hash use the percent sign 3996 39 as a prefix When assigning a list to a hash the values in the list occur in pairs as key value key value etc The assignment can also use the big arrow technique whereby the key and value are separated by 39gt39 instead of a comma Thus the list is key gt value key gt value The keys function applied to a hash returns the list of key values in no particular order The values function returns the list of values in the same order as the keys function returned In a scalar context these functions return the number of entries in the hash You can iterate over all pairs in a hash using the following loop while key Value each gahash body of loop The exists function allows you to determine if a particular key value is defined in the hash The delete function will delete the key and its value from the hash There is a special hash gaENV that includes the environment in which your program is executed Chapter 7 In the World of Regular Expressions Regular expressions specify patterns to be used for matching with strings These can be specific characters enclosed in delimiters usually 39s often combined with metacharacters and quantifiers dot matches any single character except n backslash is used to 39escape39 other metacharacters star means to repeat the previous item zero or more times plus means to repeat the previous item one or more times question mark 2 means the preceding item is optional parentheses are used to group items vertical bar I means 39or39 when it appears between two items Character class 7 sequence of characters enclosed in square brackets matches any one of these characters can specify a range a zA Z matches any letter The caret A negates the class Shortcuts 0 9 abbreviated as d w a wor character stands for a zA Z0 9 s a space character stands for ftnr These are negated with the A as quotd matches a non digit character The negations have shortcuts D W and S respectively See discussion of parentheses and back references to refer to which parts of the string actually matched the pattern Chapter 8 Matching with Regular Expressions Matches with m matches with don39t need the 39m39 any other delimiter does need the 39m39 Option Modi ers i means case insensitive match s allows newlines to be matched x allows you to add whitespace to the pattern to make it more readable multiple modifiers can be combined others will be introduced later Anchors force a pattern to match at a particular location within the string The caret A anchors at the beginning of the string and anchors at the end b matches at either end of a word a w kind of word B is a non word boundary ie matches wherever b would not Binding Operator instead of using 7 uses the string on the left for matching to the pattern on the right looks like an assignment but isn39t Interpolating into patterns A regular expression is double quote interpolated as if it were a double quoted string Match Variables Memory Parentheses not only group items but also tell the regular expression engine to remember what was in the substring that matched what was in the pattern Thus 1 includes the part of the string that matched the pattern in the first pair of parentheses 2 contains the matching part from the second pair etc There are three match variables that you always get amp and 39 The part of the string that matched a pattern is stored in amp contains what preceded the match and 39 contains whatever is after the match Noncapturing Parenteses You can follow a left parenthesis with to indicate that it is not a cpaturing parenthesis Perl 510 allows us to provide names for the captures Quanti ers means to repeat the preceding item a certain number of times so a 5 15 matches from 5 to 15 a39s fred 3 matches 3 or more repetitions of fred and w8 matches exactly 8 word characters Thus is the same as 0 the is the same as l and is the same as 0 l Precedence of metacharacters 1 Parentheses used for grouping and and memory 2 Quantifiers and numeric ones with curly braces 3 Anchors A b B and sequences of characters 4 Vertical bar I The program on page 132 can be used to test potential patterns to verify that they match input strings as expected Chapter 9 Processing Text with Regular Expressions Substitution operator 3 functions like a search and replace If the closing is followed by g then the substitution is global The i and s modify the substitution as before U forces the substitution to uppercase and L forces lowercase E turns off case shifting in lowercase l and u they affect only the next character The split operator breaks up a string based upon a separator producing a list The join function performs the opposite of split It takes two parameters the first is the separator to be inserted between the items in the array or list in the second parameter When a match m is used in a list context it produces a list of the match variables or an empty list if no matches occurred NonGreedy Quonti ers Each greedy quantifier has a non greedy counterpart itself followed with a The m modifier allows matches to include newlines think multi line Updating many files see example in text on page 143 Chapter 10 More Control Structures The unless statement is similar to an if statement except that the the statement block will be executed unless the condition is true It is like using an if statement with the condition negated or having the only statements in the else block of the if You could have an else block with an unless but it39s confusing The until loop is similar to a while loop but with the termination criteria negated until j gt i isthesameaswhile j lt i Expression Modifiers if unless until while foreoch These follow other statements for example print quotn is a negative numbernquot if n lt 0 amperror quotInvalid inputquot unless ampValid input i 2 until i gt j print quot n 2 while n lt 10 ampgreet foreach person Only a single expression is allowed on either side of the modifier Naked Block Control Structure A sequence of statements inside curly braces Variables declared within it are local to it Elsif clause Similar to Ada or Visual Basic avoids embedding if else statements inside else blocks Autoincrement and Autodecrement and operators just like C both pre and post operators Thefor Control Structure for initialization test increment loop body Loop Controls last exits the loop like break in C next jumps to the bottom of the loop like continue in C redo go back to the top of the loop block labeled blocks attach labels to loop blocks to identify them usually all caps used to refer to that loop with last next etc Ternary operator 7 expression ifitrueiexpr ififalseiexpr Logical operators ampamp means AND means OR if the left side of one of these determines the entire value of the expression then the right side is not evaluated ie it is short circuited Perl 510 provides the defined or operator
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'