Practical Report and Extraction Language (PERL)

Size: px
Start display at page:

Download "Practical Report and Extraction Language (PERL)"

Transcription

1 Practical Report and Extraction Language (PERL)

2 Introduction What is PERL? Practical Report and Extraction Language. It is an interpreted language optimized for scanning arbitrary text files, extracting information from them, and printing reports based on that information. Very powerful string handling features. Available on all platforms. Internet & Web Based Technology 2

3 Main Advantages Speed of development You can enter the program in a text file, and just run it. It is an interpretive language; no compiler is needed. It is powerful The regular expressions of Perl are extremely powerful. Uses sophisticated pattern matching techniques to scan large amounts of data very quickly. Portability Perl is a standard language and is available on all platforms. Free versions are available on the Internet. Editing Perl programs No sophisticated editing tool is needed. Any simple text editor like Notepad or vi will do. Internet & Web Based Technology 3

4 Flexibility Perl does not limit the size of your data. If memory is available, Perl can handle the whole file as a single string. Allows one to write simple programs to perform complex tasks. Internet & Web Based Technology 4

5 How to run Perl? Perl can be downloaded from the Internet. Available on almost all platforms. Assumptions: For Windows operating system, you can run Perl programs from the command prompt. Run cmd to get command prompt window. For Unix/Linux, you can run directly from the shell prompt. Internet & Web Based Technology 5

6 Working through an example Recommended steps: Create a directory/folder where you will be storing the Perl files. Using any text editor, create a file test.pl with the following content: print Good day\n ; print This is my first Perl program\n ; Execute the program by typing the following at the command prompt: perl test.pl Internet & Web Based Technology 6

7 On Unix/Linux, an additional line has to be given at the beginning of every Perl program. #!/usr/bin/perl print Good day\n ; print This is my first Perl program \n ; Internet & Web Based Technology 7

8 Variables Scalar variables A scalar variable holds a single value. Other variable types are also available (array and associative array) to be discussed later. A $ is used before the name of a variable to indicate that it is a scalar variable. $xyz = 20; Internet & Web Based Technology 8

9 Some examples: $a = 10; $name= Indranil Sen Gupta ; $average = 28.37; Variables do not have any fixed types. Variables can be printed as: print My name is $name, the average temperature is $average\n ; Internet & Web Based Technology 9

10 Data types: Perl does not specify the types of variables. It is a loosely typed language. Languages like C or java are strongly typed. Internet & Web Based Technology 10

11 Variable Interpolation A powerful feature Variable names are automatically replaced by values when they appear in double-quoted strings. An example: $stud = Rupak ; $marks = 75; print Marks obtained by $stud is $marks\n ; print Marks obtained by $stud is $marks\n ; Internet & Web Based Technology 11

12 The program will give the following output: Marks obtained by Rupak is 75 Marks obtained by $stud is $marks What do we see: If we need to do variable interpolation, use double quotes; otherwise, use single quotes. Internet & Web Based Technology 12

13 Another example: $Expense = $100 ; print The expenditure is $Expense.\n ; Internet & Web Based Technology 13

14 Expressions with Scalars Illustrated through examples (syntax similar to C) $abc = 10; $abc++; $total- -; $a = $b ** 10; # exponentiation $a = $b % 10; # modulus $balance = $balance + $deposit; $balance += $deposit; Internet & Web Based Technology 14

15 Operations on strings: Concatenation: the dot (.) is used. $a = Good ; $b = day ; $c = \n ; $total = $a.$b.$c; # concatenate the strings $a.= day\n ; # add to the string $a Internet & Web Based Technology 15

16 Arithmetic operations on strings $a = bat ; $b = $a + 1; print $a, and, $b; will print bat and bau Operations carried out based on ASCII codes. May not always be meaningful. Internet & Web Based Technology 16

17 String repetition operator (x). $a = $b x3; will concatenate three copies of $b and assign it to $a. print Ba. na x2; will print the string banana. Internet & Web Based Technology 17

18 String as a Number A string can be used in an arithmetic expression. How is the value evaluated? When converting a string to a number, Perl takes any spaces, an optional minus sign, and as many digits it can find (with dot) at the beginning of the string, and ignores everything else evaluates to Hello25 evaluates to 123 banana evaluates to 0 Internet & Web Based Technology 18

19 Escaping The character \ is used as the escape character. It escapes all of Perl s special characters (e.g., #, etc.). $num = 20; print Value of \$num is $num\n ; print The windows path is c:\\perl\\ ; Internet & Web Based Technology 19

20 Line Oriented Quoting Perl supports specification of a string spanning multiple lines. Use the marker <<. Follow it by a string, which is used to terminate the quoted material. Example: print << terminator; Hello, how are you? Good day. terminator Internet & Web Based Technology 20

21 Another example: print <HTML>\n ; print <HEAD><TITLE>Test page </TITLE></HEAD>\n ; print <BODY>\n ; print <H2>This is a test document.<h2>\n ; print </BODY></HTML> ; Internet & Web Based Technology 21

22 print << EOM; <HTML> <HEAD><TITLE>Test page </TITLE></HEAD> <BODY> <H2>This is a test document.<h2> </BODY></HTML> EOM Internet & Web Based Technology 22

23 Lists and Arrays

24 Basic Difference List is an ordered list of scalars. Array is a variable that holds a list. Each element of an array is a scalar. The size of an array: Lower limit: 0 Upper limit: no specific limit; depends on virtual memory. Internet & Web Based Technology 24

25 List Literal Examples: (10, 20, 50, 100) ( red', blue", green") ( a", 1, 2, 3, b') ($a, 12) () # empty list (10..20) # list constructor function ( A.. Z ) # same, for lettere\s Internet & Web Based Technology 25

26 Specifying Array Variable We use the # denotes an array The individual elements of the array are scalars, and can be referred to as: $months[0] # first element $months[1] # second element Internet & Web Based Technology 26

27 Initializing an Array Two ways: Specify values, separated by = ( red, green, blue, black ); Use the quote words (qw) function, that uses space as the = qw (red green blue black); Internet & Web Based Technology 27

28 Array Assignment Assign from a list of = (1, 2, = ( red, green, blue ); From the contents of another Using the qw = qw (Hello good morning); Combination of = ( brown ); Internet & Web Based Technology 28

29 Some other = = (@xyz, 6); Internet & Web Based Technology 29

30 Multiple Assignments ($x, $y, $y) = (10, 20, 30); ($x, $y) = ($y, $x); # swap elements = ( red, green, blue ); # $a gets the value red gets the value ( green, blue ) $last) = (1, 2, 3, 4); # $first gets the value 1 gets the value (2, 3, 4) # $last is undefined Internet & Web Based Technology 30

31 Number of Elements in Array Two ways: $size = $size Internet & Web Based Technology 31

32 Accessing = (1, 2, 3, 4); $first = $list[0]; $fourth = $list[3]; $list[1]++; # array becomes (1, 3, 3, 4) $x = $list[5]; # $x gets the value undef $list[2] = Go ; # array becomes (1, 2, Go, 4) Internet & Web Based Technology 32

33 The $# is the index of the last element of the = (1, 2, 3, 4, 5); print $#value \n ; # prints 4 An empty array has the value $#value = -1; Internet & Web Based Technology 33

34 shift and unshift They operate on the front of the array. shift removes the first element of the array. unshift replaces the element at the start of the array. Internet & Web Based Technology 34

35 = qw (red, blue, green, black); $first = # $first gets red, becomes # (blue, green, black) unshift (@color, white ); becomes (white, blue, green, black) Internet & Web Based Technology 35

36 pop and push They operate on the bottom of the array. pop removes the last element of the array. push replaces the last element of the array. Internet & Web Based Technology 36

37 = qw (red, blue, green, black); $first = # $first gets black, becomes # (red, blue, green) push (@color, white ); becomes (red, blue, green, white) Internet & Web Based Technology 37

38 Reversing an Array By using the reverse = ( Mina, Tina, Rina = # Reversed list stored in = # Original array is reversed. Internet & Web Based Technology 38

39 Printing an Array = qw (red, green, blue); # prints without spaces redgreenblue ; # prints with spaces red green blue Internet & Web Based Technology 39

40 Sort the Elements of an Array Using the sort keyword, by default we can sort the elements of an array lexicographically. Elements considered as = qw (red blue green = # is (black blue green red) Internet & Web Based Technology 40

41 Another = qw ( = will contain ( ) How do sort = qw ( = sort {$a <=> will contain ( ) Internet & Web Based Technology 41

42 The splice function Arguments to the splice function: The first argument is an array. The second argument is an offset (index number of the list element to begin splicing at). Third argument is the number of elements to = ( red, green, blue, black = splice (@colors, 1, 2); contains the elements removed Internet & Web Based Technology 42

43 File Handling

44 Interacting with the user Read from the keyboard (standard input). Use the file handle <STDIN>. Very simple to use. print Enter your name: ; $name = <STDIN>; # Read from keyboard print Good morning, $name. \n ; $name also contains the newline character. Need to chop it off. Internet & Web Based Technology 44

45 The chop Function The chop function removes the last character of whatever it is given to chop. In the following example, it chops the newline. print Enter your name: ; chop ($name = <STDIN>); # Read from keyboard and chop newline print Good morning, $name. \n ; chop removes the last character irrespective of whether it is a newline or not. Sometimes dangerous. Internet & Web Based Technology 45

46 Safe chopping: chomp The chomp function works similar to chop, with the difference that it chops off the last character only if it is a newline. print Enter your name: ; chomp ($name = <STDIN>); # Read from keyboard and chomp newline print Good morning, $name. \n ; Internet & Web Based Technology 46

47 File Operations Opening a file The open command opens a file and returns a file handle. For standard input, we have a predefined handle <STDIN>. $fname = /home/isg/report.txt ; open XYZ, $fname; while (<XYZ>) { print Line number $. : $_ ; } Internet & Web Based Technology 47

48 Checking the error code: $fname = /home/isg/report.txt ; open XYZ, $fname or die Error in open: $! ; while (<XYZ>) { print Line number $. : $_ ; } $. returns the line number (starting at 1) $_ returns the contents of last match $i returns the error code/message Internet & Web Based Technology 48

49 Reading from a file: The last example also illustrates file reading. The angle brackets (< >) are the line input operators. The data read goes into $_ Internet & Web Based Technology 49

50 Writing into a file: $out = /home/isg/out.txt ; open XYZ, >$out or die Error in write: $! ; for $i (1..20) { print XYZ $i :: Hello, the time is, scalar(localtime), \n ; } Internet & Web Based Technology 50

51 Appending to a file: $out = /home/isg/out.txt ; open XYZ, >>$out or die Error in write: $! ; for $i (1..20) { print XYZ $i :: Hello, the time is, scalar(localtime), \n ; } Internet & Web Based Technology 51

52 Closing a file: close XYZ; where XYZ is the file handle of the file being closed. Internet & Web Based Technology 52

53 Printing a file: This is very easy to do in Perl. $input = /home/isg/report.txt ; open IN, $input or die Error in open: $! ; while (<IN>) { print; } close IN; Internet & Web Based Technology 53

54 Command Line Arguments Perl uses a special array List of arguments passed along with the script name on the command line. Example: if you invoke Perl as: perl test.pl red blue green will be (red blue green). Printing the command line arguments: foreach (@ARGV) { print $_ \n ; } Internet & Web Based Technology 54

55 Standard File Handles <STDIN> Read from standard input (keyboard). <STDOUT> Print to standard output (screen). <STDERR> For outputting error messages. <ARGV> Reads the names of the files from the command line and opens them all. Internet & Web Based Technology 55

56 @ARGV array contains the text after the program s name in command line. <ARGV> takes each file in turn. If there is nothing specified on the command line, it reads from the standard input. Since this is very commonly used, Perl provides an abbreviation for <ARGV>, namely, < > An example is shown. Internet & Web Based Technology 56

57 $lineno = 1; while (< >) { print $lineno ++; print $lineno: $_ ; } In this program, the name of the file has to be given on the command line. perl list_lines.pl file1.txt perl list_lines.pl a.txt b.txt c.txt Internet & Web Based Technology 57

58 Control Structures

59 Introduction There are many control constructs in Perl. Similar to those in C. Would be illustrated through examples. The available constructs: for foreach if/elseif/else while do, etc. Internet & Web Based Technology 59

60 Concept of Block A statement block is a sequence of statements enclosed in matching pair of { and }. if (year == 2000) { print You have entered new millenium.\n ; } Blocks may be nested within other blocks. Internet & Web Based Technology 60

61 Definition of TRUE in Perl In Perl, only three things are considered as FALSE: The value 0 The empty string ( ) undef Everything else in Perl is TRUE. Internet & Web Based Technology 61

62 if.. else General syntax: if (test expression) { # if TRUE, do this } else { # if FALSE, do this } Internet & Web Based Technology 62

63 Examples: if ($name eq isg ) { print Welcome Indranil. \n ; } else { print You are somebody else. \n ; } if ($flag == 1) { print There has been an error. \n ; } # The else block is optional Internet & Web Based Technology 63

64 elseif Example: print Enter your id: ; chomp ($name = <STDIN>); if ($name eq isg ) { print Welcome Indranil. \n ; } elseif ($name eq bkd ) { print Welcome Bimal. \n ; } elseif ($name eq akm ) { print Welcome Arun. \n ; } else { print Sorry, I do not know you. \n ; } Internet & Web Based Technology 64

65 while Example: (Guessing the correct word) $your_choice = ; $secret_word = India ; while ($your_choice ne $secret_word) { print Enter your guess: \n ; chomp ($your_choice = <STDIN>); } print Congratulations! Mera Bharat Mahan. Internet & Web Based Technology 65

66 for Syntax same as in C. Example: for ($i=1; $i<10; $i++) { print Iteration number $i \n ; } Internet & Web Based Technology 66

67 foreach Very commonly used function that iterates over a list. = qw (red blue green); foreach $name (@colors) { print Color is $name. \n ; } We can use for in place of foreach. Internet & Web Based Technology 67

68 Example: Counting odd numbers in a = qw ( ); $count = 0; foreach $number (@xyz) { if (($number % 2) == 1) { print $number is odd. \n ; $count ++; } print Number of odd numbers is $count. \n ; } Internet & Web Based Technology 68

69 Breaking out of a loop The statement last, if it appears in the body of a loop, will cause Perl to immediately exit the loop. Used with a conditional. last if (i > 10); Internet & Web Based Technology 69

70 Skipping to end of loop For this we use the statement next. When executed, the remaining statements in the loop will be skipped, and the next iteration will begin. Also used with a conditional. Internet & Web Based Technology 70

71 Relational Operators

72 The Operators Listed Comparison Equal Not equal Greater than Less than Greater or equal Less or equal Numeric ==!= > < >= <= String eq ne gt lt ge le Internet & Web Based Technology 72

73 Logical Connectives If $a and $b are logical expressions, then the following conjunctions are supported by Perl: $a and $b $a && $b $a or $b $a $b not $a! $a Both the above alternatives are equivalent; first one is more readable. Internet & Web Based Technology 73

74 String Functions

75 The Split Function split is used to split a string into multiple pieces using a delimiter, and create a list out of it. $_= = split /:/, $_; foreach (@details) { print $_\n ; } The first parameter to split is a regular expression that specifies what to split on. The second specifies what to split. Internet & Web Based Technology 75

76 Another example: $_= Indranil ; ($name, $ , $phone) = split / /, $_; By default, split breaks a string using space as delimiter. Internet & Web Based Technology 76

77 The Join Function join is used to concatenate several elements into a single string, with a specified delimiter in between. $new = join ' ', $x1, $x2, $x3, $x4, $x5, $x6; $sep = :: ; $new = join $sep, $x1, $x2, $x4, $x5; Internet & Web Based Technology 77

78 Regular Expressions

79 Introduction One of the most useful features of Perl. What is a regular expression (RegEx)? Refers to a pattern that follows the rules of syntax. Basically specifies a chunk of text. Very powerful way to specify string patterns. Internet & Web Based Technology 79

80 An Example: without RegEx $found = 0; $_ = Hello good morning everybody ; $search = every ; foreach $word (split) { if ($word eq $search) { $found = 1; last; } } if ($found) { print Found the word every \n ; } Internet & Web Based Technology 80

81 Using RegEx $_ = Hello good morning everybody ; if ($_ =~ /every/) { print Found the word every \n ; } Very easy to use. The text between the forward slashes defines the regular expression. If we use!~ instead of =~, it means that the pattern is not present in the string. Internet & Web Based Technology 81

82 The previous example illustrates literal texts as regular expressions. Simplest form of regular expression. Point to remember: When performing the matching, all the characters in the string are considered to be significant, including punctuation and white spaces. For example, /every / will not match in the previous example. Internet & Web Based Technology 82

83 Another Simple Example $_ = Welcome to IIT Kharagpur, students ; if (/IIT K/) { print IIT K is present in the string\n ; { if (/Kharagpur students/) { print This will not match\n ; } Internet & Web Based Technology 83

84 Types of RegEx Basically two types: Matching Checking if a string contains a substring. The symbol m is used (optional if forward slash used as delimiter). Substitution Replacing a substring by another substring. The symbol s is used. Internet & Web Based Technology 84

85 Matching

86 The =~ Operator Tells Perl to apply the regular expression on the right to the value on the left. The regular expression is contained within delimiters (forward slash by default). If some other delimiter is used, then a preceding m is essential. Internet & Web Based Technology 86

87 Examples $string = Good day ; if ($string =~ m/day/) { print Match successful \n"; } if ($string =~ /day/) { print Match successful \n"; } Both forms are equivalent. The m in the first form is optional. Internet & Web Based Technology 87

88 $string = Good day ; if ($string =~ m@day@) { print Match successful \n"; } if ($string =~ m[day[ ) { print Match successful \n"; } Both forms are equivalent. The character following m is the delimiter. Internet & Web Based Technology 88

89 Character Class Use square brackets to specify any value in the list of possible values. my $string = Some test string 1234"; if ($string =~ /[ ]/) { print "found a number \n"; } if ($string =~ /[aeiou]/) { print "Found a vowel \n"; } if ($string =~ /[ ABCDEF]/) { print "Found a hex digit \n"; } Internet & Web Based Technology 89

90 Character Class Negation Use ^ at the beginning of the character class to specify any single element that is not one of these values. my $string = Some test string 1234"; if ($string =~ /[^aeiou]/) { print "Found a consonant\n"; } Internet & Web Based Technology 90

91 Pattern Abbreviations Useful in common cases. \d \w \s \D \W \S Anything except newline (\n) A digit, same as [0-9] A word character, [0-9a-zA-Z_] A space character (tab, space, etc) Not a digit, same as [^0-9] Not a word character Not a space character Internet & Web Based Technology 91

92 $string = Good and bad days"; if ($string =~ /d..s/) { print "Found something like days\n"; } if ($string =~ /\w\w\w\w\s/) { print "Found a four-letter word!\n"; } Internet & Web Based Technology 92

93 Anchors Three ways to define an anchor: ^ :: anchors to the beginning of string $ :: anchors to the end of the string \b :: anchors to a word boundary Internet & Web Based Technology 93

94 if ($string =~ /^\w/) :: does string start with a word character? if ($string =~ /\d$/) :: does string end with a digit? if ($string =~ /\bgood\b/) :: Does string contain the word Good? Internet & Web Based Technology 94

95 Multipliers There are three multiplier characters. * :: Find zero or more occurrences + :: Find one or more occurrences? :: Find zero or one occurrence Some example usages: $string =~ /^\w+/; $string =~ /\d?/; $string =~ /\b\w+\s+/; $string =~ /\w+\s?$/; Internet & Web Based Technology 95

96 Substitution

97 Basic Usage Uses the s character. Basic syntax is: $new =~ s/pattern_to_match/new_pattern/; What this does? Looks for pattern_to_match in $new and, if found, replaces it with new_pattern. It looks for the pattern once. That is, only the first occurrence is replaced. There is a way to replace all occurrences (to be discussed shortly). Internet & Web Based Technology 97

98 Examples $xyz = Rama and Lakshman went to the forest ; $xyz =~ s/lakshman/bharat/; $xyz =~ s/r\w+a/bharat/; $xyz =~ s/[aeiou]/i/; $abc = A year has 11 months \n ; $abc =~ s/\d+/12/; $abc =~ s /\n$/ /; Internet & Web Based Technology 98

99 Common Modifiers Two such modifiers are defined: /i :: ignore case /g :: match/substitute all occurrences $string = Ram and Shyam are very honest"; if ($string =~ /RAM/i) { print Ram is present in the string ; } $string =~ s/m/j/g; # Ram -> Raj, Shyam -> Shyaj Internet & Web Based Technology 99

100 Use of Memory in RegEx We can use parentheses to capture a piece of matched text for later use. Perl memorizes the matched texts. Multiple sets of parentheses can be used. How to recall the captured text? Use \1, \2, \3, etc. if still in RegEx. Use $1, $2, $3 if after the RegEx. Internet & Web Based Technology 100

101 Examples $string = Ram and Shyam are honest"; $string =~ /^(\w+)/; print $1, "\n"; # prints Ra\n $string =~ /(\w+)$/; print $1, "\n"; # prints st\n $string =~ /^(\w+)\s+(\w+)/; print "$1 $2\n"; # prints Ramnd Shyam are honest ; Internet & Web Based Technology 101

102 $string = Ram and Shyam are very poor"; if ($string =~ /(\w)\1/) { print "found 2 in a row\n"; } if ($string =~ /(\w+).*\1/) { print "found repeat\n"; } $string =~ s/(\w+) and (\w+)/$2 and $1/; Internet & Web Based Technology 102

103 Example 1 validating user input print Enter age (or 'q' to quit): "; chomp (my $age = <STDIN>); exit if ($age =~ /^q$/i); if ($age =~ /\D/) { print "$age is a non-number!\n"; } Internet & Web Based Technology 103

104 Example 2: validation contd. File has 2 columns, name and age, delimited by one or more spaces. Can also have blank lines or commented lines (start with #). open IN, $file or die "Cannot open $file: $!"; while (my $line = <IN>) { chomp $line; next if ($line =~ /^\s*$/ or $line =~ /^\s*#/); my ($name, $age) = split /\s+/, $line; print The age of $name is $age. \n"; } Internet & Web Based Technology 104

105 Some Special Variables

106 $&, $` and $ What is $&? It represents the string matched by the last successful pattern match. What is $`? It represents the string preceding whatever was matched by the last successful pattern match. What is $? It represents the string following whatever was matched by the last successful pattern match. Internet & Web Based Technology 106

107 Example: $_ = 'abcdefghi'; /def/; print "$\`:$&:$'\n"; # prints abc:def:ghi Internet & Web Based Technology 107

108 So actually. S` represents pre match $& represents present match $ represents post match Internet & Web Based Technology 108

109 Associative Arrays

110 Introduction Associative arrays, also known as hashes. Similar to a list Every list element consists of a pair, a hash key and a value. Hash keys must be unique. Accessing an element Unlike an array, an element value can be found out by specifying the hash key value. Associative search. A hash array name must begin with a %. Internet & Web Based Technology 110

111 Specifying Hash Array Two ways to specify: Specifying hash keys and values, in proper sequence. %directory = ( Rabi, , Chandan, , Atul, , Sruti, ); Internet & Web Based Technology 111

112 Using the => operator. %directory = ( Rabi => , Chandan => , Atul => , Sruti => ); Whatever appears on the left hand side of => is treated as a double-quoted string. Internet & Web Based Technology 112

113 Conversion Array <=> Hash An array can be converted to = qw (Rabi Chandan Atul Sruti ); %directory A hash can be converted to an = %directory; Internet & Web Based Technology 113

114 Accessing a Hash Element Given the hash key, the value can be accessed using { }. = qw (Rabi Chandan Atul Sruti ); %directory print Atul s number is $directory{ Atul } \n ; Internet & Web Based Technology 114

115 Modifying a Value By simple = qw (Rabi Chandan Atul Sruti ); %directory $directory{sruti} = ; $directory{ Chandan } ++; Internet & Web Based Technology 115

116 Deleting an Entry A (hash key, value) pair can be deleted from a hash array using the delete function. Hash key has to be = qw (Rabi Chandan Atul Sruti ); %directory delete $directory{atul}; Internet & Web Based Technology 116

117 Swapping Keys and Values Why needed? Suppose we want to search for a person, given the phone = qw (Rabi Chandan Atul Sruti ); %directory %revdir = reverse %directory; print $revdir{237221} \n ; Internet & Web Based Technology 117

118 Using Functions keys, values keys returns all the hash keys as a list. values returns all the values as a = qw (Rabi Chandan Atul Sruti ); = keys = values %directory; Internet & Web Based Technology 118

119 An Example List all person names and telephone = qw (Rabi Chandan Atul Sruti ); %directory foreach $name (keys %directory) { print $name \t $directory{$name} \n ; } Internet & Web Based Technology 119

120 Subroutines

121 Introduction A subroutine.. Is a user-defined function. Allows code reuse. Define ones, use multiple times. Internet & Web Based Technology 121

122 How to use? Defining a subroutine sub test_sub { # the body of the subroutine goes here #.. } Calling a subroutine Use the & prefix to call a subroutine. &test_sub; &gcd ($val1, $val2); # Two parameters However, the & is optional. Internet & Web Based Technology 122

123 Subroutine Return Values Use the return statement. This is also optional. If the keyword return is omitted, Perl functions return the last value evaluated. A subroutine can also return a non-scalar. Some examples are given next. Internet & Web Based Technology 123

124 Example 1 $name = Indranil'; welcome(); welcome_namei(); exit; # call the first sub # call the second sub sub welcome { print "hi there\n"; } sub welcome_name { print "hi $name\n"; } # uses global $name variable Internet & Web Based Technology 124

125 Example 2 # Return a non-scalar sub return_alpha_and_beta { return ($alpha, $beta); } $alpha = 15; $beta = = return_alpha_and_beta; gets (5,6) Internet & Web Based Technology 125

126 Passing Arguments All arguments are passed into a Perl function through the special array $_. Thus, we can send as many arguments as we want. Individual arguments can also be accessed as $_[0], $_[1], $_[2], etc. Internet & Web Based Technology 126

127 Example 3 # Two different ways to write a subroutine to add two numbers sub add_ver1 { ($first, $second) return ($first + $second); } sub add_ver2 { return $_[0] + $_[1]; # $_[0] and $_[1] are the first two # elements } Internet & Web Based Technology 127

128 Example 4 $total = find_total (5, 10, -12, 7, 40); sub find_total { # adds all numbers passed to the sub $sum = 0; for $num (@_) { $sum += $num; } return $sum; } Internet & Web Based Technology 128

129 my variables We can define local variables using the my keyword. Confines a variable to a region of code (within a block { } ). my variable s storage is freed whenever the variable goes out of scope. All variables in Perl is by default global. Internet & Web Based Technology 129

130 Example 5 $sum = 7; $total = add_any (20, 10, -15); # $total gets 15 sub add_any { my $sum = 0; # local variable, won't interfere # with global $sum } for my $num (@_ ) { $sum += $num; } return $sum; Internet & Web Based Technology 130

131 Writing CGI Scripts in Perl

132 Introduction Perl provides with a number of facilities to facilitate writing of CGI scripts. Standard library modules. Included as part of the Perl distribution. No need to install them separately. #!/usr/bin/perl use CGI qw (:standard); Internet & Web Based Technology 132

133 Some of the functions included in the CGI.pm (.pm is optional) are: header This prints out the Content-type header. With no arguments, the type is assumed to be text/html. start_html This prints out the <html>, <head>, <title> and <body> tags. Accepts optional arguments. Internet & Web Based Technology 133

134 end_html This prints out the closing HTML tags, </body>, >/html>. Typical usages and arguments would be illustrated through examples. Internet & Web Based Technology 134

135 Example 1 (without using CGI.pm) #!/usr/bin/perl print <<TO_END; Content-type: text/html <HTML> <HEAD> <TITLE> Server Details </TITLE> </HEAD> <BODY> Server name: $ENV{SERVER_NAME} <BR> Server port number: $ENV{SERVER_PORT} <BR> Server protocol: $ENV{SERVER_PROTOCOL} </BODY> </HTML> TO_END Internet & Web Based Technology 135

136 Example 2 (using CGI.pm) #!/usr/bin/perl -wt use CGI qw(:standard); print header ( text/html ); print start_html ("Hello World"); print "<h2>hello, world!</h2>\n"; print end_html; Internet & Web Based Technology 136

137 Example 3: Decoding Form Input sub parse_form_data { my %form_data; my $name_value; = split /&/, $ENV{QUERY_STRING}; if ( $ENV{REQUEST_METHOD} eq POST ) { my $query = ; read (STDIN, $query, $ENV{CONTENT_LENGTH}); split /&/, $query; } Internet & Web Based Technology 137

138 foreach $name_value { my ($name, $value) = split /=/, $name_value; $name =~ tr/+/ /; $name =~ s/%([\da-f][\da-f])/chr (hex($1))/egi; $value =~ tr/+/ /; $value =~ s/%([\da-f][\da-f])/chr (hex($1))/egi; } $form_data{$name} = $value; } return %form_data; Internet & Web Based Technology 138

139 Using CGI.pm The decoded form value can be directly accessed as: $value = param ( fieldname ); An equivalent Perl code as in the last example using CGI.pm Shown in next slide. Internet & Web Based Technology 139

140 Example 4 #!/usr/bin/perl -wt use CGI qw(:standard); my %form_data; foreach my $name (param() ) { $form_data {$name} = param($name); } Internet & Web Based Technology 140

141 Example 5: sending mail #!/usr/bin/perl -wt use CGI qw(:standard); print header; print start_html ( Response to Guestbook ); $ENV{PATH} = /usr/sbin ; # to locate sendmail open (MAIL, /usr/sbin/sendmail oi t ); # open the pipe to sendmail my $recipient = xyz@hotmail.com ; print MAIL To: $recipient\n ; print MAIL From: isg\@cse.iitkgp.ac.in\n ; print MAIL Subject: Submitted data\n\n ; Internet & Web Based Technology 141

142 foreach my $xyz (param()) { print MAIL $xyz =, param($xyz), \n ; } close (MAIL); print <<EOM; <h2>thanks for the comments</h2> <p>hope you visit again.</p> EOM print end_html; Internet & Web Based Technology 142

Indian Institute of Technology Kharagpur. PERL Part III. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

Indian Institute of Technology Kharagpur. PERL Part III. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Indian Institute of Technology Kharagpur PERL Part III Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Kharagpur, INDIA Lecture 23: PERL Part III On completion, the student will be able

More information

Indian Institute of Technology Kharagpur. PERL Part II. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

Indian Institute of Technology Kharagpur. PERL Part II. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Indian Institute of Technology Kharagpur PERL Part II Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Kharagpur, INDIA Lecture 22: PERL Part II On completion, the student will be able

More information

(Refer Slide Time: 01:12)

(Refer Slide Time: 01:12) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #22 PERL Part II We continue with our discussion on the Perl

More information

Perl. Interview Questions and Answers

Perl. Interview Questions and Answers and Answers Prepared by Abhisek Vyas Document Version 1.0 Team, www.sybaseblog.com 1 of 13 Q. How do you separate executable statements in perl? semi-colons separate executable statements Example: my(

More information

Pathologically Eclectic Rubbish Lister

Pathologically Eclectic Rubbish Lister Pathologically Eclectic Rubbish Lister 1 Perl Design Philosophy Author: Reuben Francis Cornel perl is an acronym for Practical Extraction and Report Language. But I guess the title is a rough translation

More information

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1 CSCI 4152/6509 Natural Language Processing Perl Tutorial CSCI 4152/6509 Vlado Kešelj CSCI 4152/6509, Perl Tutorial 1 created in 1987 by Larry Wall About Perl interpreted language, with just-in-time semi-compilation

More information

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list.

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list. Arrays Perl arrays store lists of scalar values, which may be of different types. They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list. A list literal

More information

COMS 3101 Programming Languages: Perl. Lecture 2

COMS 3101 Programming Languages: Perl. Lecture 2 COMS 3101 Programming Languages: Perl Lecture 2 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl Lecture Outline Control Flow (continued) Input / Output Subroutines Concepts:

More information

PERL Scripting - Course Contents

PERL Scripting - Course Contents PERL Scripting - Course Contents Day - 1 Introduction to PERL Comments Reading from Standard Input Writing to Standard Output Scalar Variables Numbers and Strings Use of Single Quotes and Double Quotes

More information

A control expression must evaluate to a value that can be interpreted as true or false.

A control expression must evaluate to a value that can be interpreted as true or false. Control Statements Control Expressions A control expression must evaluate to a value that can be interpreted as true or false. How a control statement behaves depends on the value of its control expression.

More information

Regular Expressions. Regular expressions are a powerful search-and-replace technique that is widely used in other environments (such as Unix and Perl)

Regular Expressions. Regular expressions are a powerful search-and-replace technique that is widely used in other environments (such as Unix and Perl) Regular Expressions Regular expressions are a powerful search-and-replace technique that is widely used in other environments (such as Unix and Perl) JavaScript started supporting regular expressions in

More information

1. Introduction. 2. Scalar Data

1. Introduction. 2. Scalar Data 1. Introduction What Does Perl Stand For? Why Did Larry Create Perl? Why Didn t Larry Just Use Some Other Language? Is Perl Easy or Hard? How Did Perl Get to Be So Popular? What s Happening with Perl Now?

More information

Outline. CS3157: Advanced Programming. Feedback from last class. Last plug

Outline. CS3157: Advanced Programming. Feedback from last class. Last plug Outline CS3157: Advanced Programming Lecture #2 Jan 23 Shlomo Hershkop shlomo@cs.columbia.edu Feedback Introduction to Perl review and continued Intro to Regular expressions Reading Programming Perl pg

More information

Introduction to Perl. Perl Background. Sept 24, 2007 Class Meeting 6

Introduction to Perl. Perl Background. Sept 24, 2007 Class Meeting 6 Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by Lenwood Heath, Virginia Tech 2004 Perl Background Practical Extraction and Report Language (Perl) Created by Larry Wall, mid-1980's

More information

Programming Perls* Objective: To introduce students to the perl language.

Programming Perls* Objective: To introduce students to the perl language. Programming Perls* Objective: To introduce students to the perl language. Perl is a language for getting your job done. Making Easy Things Easy & Hard Things Possible Perl is a language for easily manipulating

More information

Introduction to Perl. c Sanjiv K. Bhatia. Department of Mathematics & Computer Science University of Missouri St. Louis St.

Introduction to Perl. c Sanjiv K. Bhatia. Department of Mathematics & Computer Science University of Missouri St. Louis St. Introduction to Perl c Sanjiv K. Bhatia Department of Mathematics & Computer Science University of Missouri St. Louis St. Louis, MO 63121 Contents 1 Introduction 1 2 Getting started 1 3 Writing Perl scripts

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

8/13/ /printqp.php?heading=II BSc [ ], Semester III, Allied: COMPUTER PROGRAMMING-PERL -309C&qname=309C

8/13/ /printqp.php?heading=II BSc [ ], Semester III, Allied: COMPUTER PROGRAMMING-PERL -309C&qname=309C Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'

More information

Shell Start-up and Configuration Files

Shell Start-up and Configuration Files ULI101 Week 10 Lesson Overview Shell Start-up and Configuration Files Shell History Alias Statement Shell Variables Introduction to Shell Scripting Positional Parameters echo and read Commands if and test

More information

Scripting Languages Perl Basics. Course: Hebrew University

Scripting Languages Perl Basics. Course: Hebrew University Scripting Languages Perl Basics Course: 67557 Hebrew University אליוט יפה Jaffe Lecturer: Elliot FMTEYEWTK Far More Than Everything You've Ever Wanted to Know Perl Pathologically Eclectic Rubbish Lister

More information

Modularity and Reusability I. Functions and code reuse

Modularity and Reusability I. Functions and code reuse Modularity and Reusability I Functions and code reuse Copyright 2006 2009 Stewart Weiss On being efficient When you realize that a piece of Perl code that you wrote may be useful in future programs, you

More information

Hands-On Perl Scripting and CGI Programming

Hands-On Perl Scripting and CGI Programming Hands-On Course Description This hands on Perl programming course provides a thorough introduction to the Perl programming language, teaching attendees how to develop and maintain portable scripts useful

More information

Perl and Python ESA 2007/2008. Eelco Schatborn 27 September 2007

Perl and Python ESA 2007/2008. Eelco Schatborn 27 September 2007 Perl and Python ESA 2007/2008 Eelco Schatborn eelco@os3.nl 27 September 2007 ESA: Perl Vandaag: 1. Perl introduction 2. Basic Perl: types, variables, statements,... 3. Object Oriented Perl 4. Documentation

More information

COMS 3101 Programming Languages: Perl. Lecture 1

COMS 3101 Programming Languages: Perl. Lecture 1 COMS 3101 Programming Languages: Perl Lecture 1 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl What is Perl? Perl is a high level language initially developed as a scripting

More information

Bourne Shell Reference

Bourne Shell Reference > Linux Reviews > Beginners: Learn Linux > Bourne Shell Reference Bourne Shell Reference found at Br. David Carlson, O.S.B. pages, cis.stvincent.edu/carlsond/cs330/unix/bshellref - Converted to txt2tags

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

A shell can be used in one of two ways:

A shell can be used in one of two ways: Shell Scripting 1 A shell can be used in one of two ways: A command interpreter, used interactively A programming language, to write shell scripts (your own custom commands) 2 If we have a set of commands

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Perl Scripting. Students Will Learn. Course Description. Duration: 4 Days. Price: $2295

Perl Scripting. Students Will Learn. Course Description. Duration: 4 Days. Price: $2295 Perl Scripting Duration: 4 Days Price: $2295 Discounts: We offer multiple discount options. Click here for more info. Delivery Options: Attend face-to-face in the classroom, remote-live or on-demand streaming.

More information

Perl Regular Expressions. Perl Patterns. Character Class Shortcuts. Examples of Perl Patterns

Perl Regular Expressions. Perl Patterns. Character Class Shortcuts. Examples of Perl Patterns Perl Regular Expressions Unlike most programming languages, Perl has builtin support for matching strings using regular expressions called patterns, which are similar to the regular expressions used in

More information

JavaScript CS 4640 Programming Languages for Web Applications

JavaScript CS 4640 Programming Languages for Web Applications JavaScript CS 4640 Programming Languages for Web Applications 1 How HTML, CSS, and JS Fit Together {css} javascript() Content layer The HTML gives the page structure and adds semantics Presentation

More information

Essentials for Scientific Computing: Bash Shell Scripting Day 3

Essentials for Scientific Computing: Bash Shell Scripting Day 3 Essentials for Scientific Computing: Bash Shell Scripting Day 3 Ershaad Ahamed TUE-CMS, JNCASR May 2012 1 Introduction In the previous sessions, you have been using basic commands in the shell. The bash

More information

(Refer Slide Time: 01:40)

(Refer Slide Time: 01:40) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #25 Javascript Part I Today will be talking about a language

More information

Perl. Many of these conflict with design principles of languages for teaching.

Perl. Many of these conflict with design principles of languages for teaching. Perl Perl = Practical Extraction and Report Language Developed by Larry Wall (late 80 s) as a replacement for awk. Has grown to become a replacement for awk, sed, grep, other filters, shell scripts, C

More information

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

More Scripting and Regular Expressions. Todd Kelley CST8207 Todd Kelley 1

More Scripting and Regular Expressions. Todd Kelley CST8207 Todd Kelley 1 More Scripting and Regular Expressions Todd Kelley kelleyt@algonquincollege.com CST8207 Todd Kelley 1 Regular Expression Summary Regular Expression Examples Shell Scripting 2 Do not confuse filename globbing

More information

A Big Step. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

A Big Step. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers A Big Step Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers Copyright 2006 2009 Stewart Weiss What a shell really does Here is the scoop on shells. A shell is a program

More information

Perl. Perl. Perl. Which Perl

Perl. Perl. Perl. Which Perl Perl Perl Perl = Practical Extraction and Report Language Developed by Larry Wall (late 80 s) as a replacement for awk. Has grown to become a replacement for awk, sed, grep, other filters, shell scripts,

More information

Scripting Languages. Diana Trandabăț

Scripting Languages. Diana Trandabăț Scripting Languages Diana Trandabăț Master in Computational Linguistics - 1 st year 2017-2018 Today s lecture What is Perl? How to install Perl? How to write Perl progams? How to run a Perl program? perl

More information

What is PERL?

What is PERL? Perl For Beginners What is PERL? Practical Extraction Reporting Language General-purpose programming language Creation of Larry Wall 1987 Maintained by a community of developers Free/Open Source www.cpan.org

More information

JavaScript Functions, Objects and Array

JavaScript Functions, Objects and Array JavaScript Functions, Objects and Array Defining a Function A definition starts with the word function. A name follows that must start with a letter or underscore, followed by any number of letters, digits,

More information

PERL. Pattern Extraction and Reporting Language. Example: $x = 10 $value = $x + 1 $word = "hello"

PERL. Pattern Extraction and Reporting Language. Example: $x = 10 $value = $x + 1 $word = hello PERL Pattern Extraction and Reporting Language Example: Web page serving through CGI: Perl is used extensively in serving up content when run in concert with a web-server. Talking to web sites and reporting

More information

Beginning Perl for Bioinformatics. Steven Nevers Bioinformatics Research Group Brigham Young University

Beginning Perl for Bioinformatics. Steven Nevers Bioinformatics Research Group Brigham Young University Beginning Perl for Bioinformatics Steven Nevers Bioinformatics Research Group Brigham Young University Why Use Perl? Interpreted language (quick to program) Easy to learn compared to most languages Designed

More information

Scripting. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers

Scripting. Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers Scripting Shell Scripts, I/O Redirection, Ownership and Permission Concepts, and Binary Numbers Adapted from Practical Unix and Programming Hunter College Copyright 2006 2009 Stewart Weiss What a shell

More information

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1 Shell Scripting Todd Kelley kelleyt@algonquincollege.com CST8207 Todd Kelley 1 If we have a set of commands that we want to run on a regular basis, we could write a script A script acts as a Linux command,

More information

Introductory Perl. What is Perl?

Introductory Perl. What is Perl? Introductory Perl Boston University Office of Information Technology Course Number: 4080 Course Coordinator: Timothy Kohl Last Modified: 08/29/05 What is Perl? Perl stands for Practical Extraction and

More information

COMP 110 Project 1 Programming Project Warm-Up Exercise

COMP 110 Project 1 Programming Project Warm-Up Exercise COMP 110 Project 1 Programming Project Warm-Up Exercise Creating Java Source Files Over the semester, several text editors will be suggested for students to try out. Initially, I suggest you use JGrasp,

More information

Welcome to Research Computing Services training week! November 14-17, 2011

Welcome to Research Computing Services training week! November 14-17, 2011 Welcome to Research Computing Services training week! November 14-17, 2011 Monday intro to Perl, Python and R Tuesday learn to use Titan Wednesday GPU, MPI and profiling Thursday about RCS and services

More information

Beginning Perl. Third Edition. Apress. JAMES LEE with SIMON COZENS

Beginning Perl. Third Edition. Apress. JAMES LEE with SIMON COZENS Beginning Perl Third Edition JAMES LEE with SIMON COZENS Apress About the Author... About the Technical Reviewers Acknowledgements Suitrod yetion «. xvi xvii xviii «xix. Chapter 1: First Steps in Perl..

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Arrays (Lists) # or, = ("first string", "2nd string", 123);

Arrays (Lists) # or, = (first string, 2nd string, 123); Arrays (Lists) An array is a sequence of scalars, indexed by position (0,1,2,...) The whole array is denoted by @array Individual array elements are denoted by $array[index] $#array gives the index of

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

PHP by Pearson Education, Inc. All Rights Reserved.

PHP by Pearson Education, Inc. All Rights Reserved. PHP 1992-2012 by Pearson Education, Inc. All Client-side Languages User-agent (web browser) requests a web page JavaScript is executed on PC http request Can affect the Browser and the page itself http

More information

Basic Linux (Bash) Commands

Basic Linux (Bash) Commands Basic Linux (Bash) Commands Hint: Run commands in the emacs shell (emacs -nw, then M-x shell) instead of the terminal. It eases searching for and revising commands and navigating and copying-and-pasting

More information

More Perl. CS174 Chris Pollett Oct 25, 2006.

More Perl. CS174 Chris Pollett Oct 25, 2006. More Perl CS174 Chris Pollett Oct 25, 2006. Outline Loops Arrays Hashes Functions Selection Redux Last day we learned about how if-else works in Perl. Perl does not have a switch statement Like Javascript,

More information

CS 230 Programming Languages

CS 230 Programming Languages CS 230 Programming Languages 09 / 16 / 2013 Instructor: Michael Eckmann Today s Topics Questions/comments? Continue Syntax & Semantics Mini-pascal Attribute Grammars More Perl A more complex grammar Let's

More information

CSC Web Programming. Introduction to JavaScript

CSC Web Programming. Introduction to JavaScript CSC 242 - Web Programming Introduction to JavaScript JavaScript JavaScript is a client-side scripting language the code is executed by the web browser JavaScript is an embedded language it relies on its

More information

UNIX Shell Programming

UNIX Shell Programming $!... 5:13 $$ and $!... 5:13.profile File... 7:4 /etc/bashrc... 10:13 /etc/profile... 10:12 /etc/profile File... 7:5 ~/.bash_login... 10:15 ~/.bash_logout... 10:18 ~/.bash_profile... 10:14 ~/.bashrc...

More information

Regular expressions and case insensitivity

Regular expressions and case insensitivity Regular expressions and case insensitivity As previously mentioned, you can make matching case insensitive with the i flag: /\b[uu][nn][ii][xx]\b/; /\bunix\b/i; # explicitly giving case folding # using

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Bamuengine.com. Chapter 14. Perl The Mater Manipulator

Bamuengine.com. Chapter 14. Perl The Mater Manipulator Chapter 14. Perl The Mater Manipulator Introduciton The following sections tell you what Perl is, the variables and operators in perl, the string handling functions. The chapter also discusses file handling

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

# Extract the initial substring of $text that is delimited by # two (unescaped) instances of the first character in $delim.

# Extract the initial substring of $text that is delimited by # two (unescaped) instances of the first character in $delim. NAME SYNOPSIS Text::Balanced - Extract delimited text sequences from strings. use Text::Balanced qw ( extract_delimited extract_bracketed extract_quotelike extract_codeblock extract_variable extract_tagged

More information

BIOS 546 Midterm March 26, Write the line of code that all Perl programs on biolinx must start with so they can be executed.

BIOS 546 Midterm March 26, Write the line of code that all Perl programs on biolinx must start with so they can be executed. 1. What values are false in Perl? BIOS 546 Midterm March 26, 2007 2. Write the line of code that all Perl programs on biolinx must start with so they can be executed. 3. How do you make a comment in Perl?

More information

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell.

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell. Command Interpreters A command interpreter is a program that executes other programs. Aim: allow users to execute the commands provided on a computer system. Command interpreters come in two flavours:

More information

Bashed One Too Many Times. Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009

Bashed One Too Many Times. Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009 Bashed One Too Many Times Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009 What is a Shell? The shell interprets commands and executes them It provides you with an environment

More information

CMSC 331 Final Exam Fall 2013

CMSC 331 Final Exam Fall 2013 CMSC 331 Final Exam Fall 2013 Name: UMBC username: You have two hours to complete this closed book exam. Use the backs of these pages if you need more room for your answers. Describe any assumptions you

More information

Programming Fundamentals

Programming Fundamentals Programming Fundamentals Computers are really very dumb machines -- they only do what they are told to do. Most computers perform their operations on a very primitive level. The basic operations of a computer

More information

CGI Programming. What is "CGI"?

CGI Programming. What is CGI? CGI Programming What is "CGI"? Common Gateway Interface A means of running an executable program via the Web. CGI is not a Perl-specific concept. Almost any language can produce CGI programs even C++ (gasp!!)

More information

Perl Programming. Bioinformatics Perl Programming

Perl Programming. Bioinformatics Perl Programming Bioinformatics Perl Programming Perl Programming Regular expressions A regular expression is a pattern to be matched against s string. This results in either a failure or success. You may wish to go beyond

More information

Vi & Shell Scripting

Vi & Shell Scripting Vi & Shell Scripting Comp-206 : Introduction to Week 3 Joseph Vybihal Computer Science McGill University Announcements Sina Meraji's office hours Trottier 3rd floor open area Tuesday 1:30 2:30 PM Thursday

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Beginning Perl. Mark Senn. September 11, 2007

Beginning Perl. Mark Senn. September 11, 2007 GoBack Beginning Perl Mark Senn September 11, 2007 Overview Perl is a popular programming language used to write systen software, text processing tools, World Wide Web CGI programs, etc. It was written

More information

Shell Programming (bash)

Shell Programming (bash) Shell Programming Shell Programming (bash) Commands run from a file in a subshell A great way to automate a repeated sequence of commands. File starts with #!/bin/bash absolute path to the shell program

More information

SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7

SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7 SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7 Hi everyone once again welcome to this lecture we are actually the course is Linux programming and scripting we have been talking about the Perl, Perl

More information

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual Contents 1 Introduction...2 2 Lexical Conventions...2 3 Types...3 4 Syntax...3 5 Expressions...4 6 Declarations...8 7 Statements...9

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus INTERNAL ASSESSMENT TEST - III Date : 09-11-2015 Marks : 0 Subject & Code : USP & 15CS36 Class : III ISE A & B Name of faculty : Prof. Ajoy Kumar Note: Solutions to ALL Questions Questions 1 a. Explain

More information

IT441. Network Services Administration. Perl: File Handles

IT441. Network Services Administration. Perl: File Handles IT441 Network Services Administration Perl: File Handles Comment Blocks Perl normally treats lines beginning with a # as a comment. Get in the habit of including comments with your code. Put a comment

More information

Lecture 5. Essential skills for bioinformatics: Unix/Linux

Lecture 5. Essential skills for bioinformatics: Unix/Linux Lecture 5 Essential skills for bioinformatics: Unix/Linux UNIX DATA TOOLS Text processing with awk We have illustrated two ways awk can come in handy: Filtering data using rules that can combine regular

More information

T-( )-MALV, Natural Language Processing The programming language Perl

T-( )-MALV, Natural Language Processing The programming language Perl T-(538 725)-MALV, Natural Language Processing The programming language Perl Hrafn Loftsson 1 Hannes Högni Vilhjálmsson 1 1 School of Computer Science, Reykjavik University September 2010 Outline 1 Perl

More information

Shells and Shell Programming

Shells and Shell Programming Shells and Shell Programming 1 Shells A shell is a command line interpreter that is the interface between the user and the OS. The shell: analyzes each command determines what actions are to be performed

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

9.1 Origins and Uses of Perl

9.1 Origins and Uses of Perl 9.1 Origins and Uses of Perl - Began in the late 1980s as a more powerful replacement for the capabilities of awk (text file processing) and sh (UNIX system administration) - Now includes sockets for communications

More information

PHP. Interactive Web Systems

PHP. Interactive Web Systems PHP Interactive Web Systems PHP PHP is an open-source server side scripting language. PHP stands for PHP: Hypertext Preprocessor One of the most popular server side languages Second most popular on GitHub

More information

Cisco IOS Shell. Finding Feature Information. Prerequisites for Cisco IOS.sh. Last Updated: December 14, 2012

Cisco IOS Shell. Finding Feature Information. Prerequisites for Cisco IOS.sh. Last Updated: December 14, 2012 Cisco IOS Shell Last Updated: December 14, 2012 The Cisco IOS Shell (IOS.sh) feature provides shell scripting capability to the Cisco IOS command-lineinterface (CLI) environment. Cisco IOS.sh enhances

More information

This page covers the very basics of understanding, creating and using regular expressions ('regexes') in Perl.

This page covers the very basics of understanding, creating and using regular expressions ('regexes') in Perl. NAME DESCRIPTION perlrequick - Perl regular expressions quick start Perl version 5.16.2 documentation - perlrequick This page covers the very basics of understanding, creating and using regular expressions

More information

Lecture Outline. COMP-421 Compiler Design. What is Lex? Lex Specification. ! Lexical Analyzer Lex. ! Lex Examples. Presented by Dr Ioanna Dionysiou

Lecture Outline. COMP-421 Compiler Design. What is Lex? Lex Specification. ! Lexical Analyzer Lex. ! Lex Examples. Presented by Dr Ioanna Dionysiou Lecture Outline COMP-421 Compiler Design! Lexical Analyzer Lex! Lex Examples Presented by Dr Ioanna Dionysiou Figures and part of the lecture notes taken from A compact guide to lex&yacc, epaperpress.com

More information

Regular expressions and case insensitivity

Regular expressions and case insensitivity Regular expressions and case insensitivity As previously mentioned, you can make matching case insensitive with the i flag: /\b[uu][nn][ii][xx]\b/; # explicitly giving case folding /\bunix\b/i; # using

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy

COMP 2718: Shell Scripts: Part 1. By: Dr. Andrew Vardy COMP 2718: Shell Scripts: Part 1 By: Dr. Andrew Vardy Outline Shell Scripts: Part 1 Hello World Shebang! Example Project Introducing Variables Variable Names Variable Facts Arguments Exit Status Branching:

More information

psed [-an] script [file...] psed [-an] [-e script] [-f script-file] [file...]

psed [-an] script [file...] psed [-an] [-e script] [-f script-file] [file...] NAME SYNOPSIS DESCRIPTION OPTIONS psed - a stream editor psed [-an] script [file...] psed [-an] [-e script] [-f script-file] [file...] s2p [-an] [-e script] [-f script-file] A stream editor reads the input

More information

Chapter 2, Part I Introduction to C Programming

Chapter 2, Part I Introduction to C Programming Chapter 2, Part I Introduction to C Programming C How to Program, 8/e, GE 2016 Pearson Education, Ltd. All rights reserved. 1 2016 Pearson Education, Ltd. All rights reserved. 2 2016 Pearson Education,

More information

Scripting. More Shell Scripts. Adapted from Practical Unix and Programming Hunter College

Scripting. More Shell Scripts. Adapted from Practical Unix and Programming Hunter College Scripting More Shell Scripts Adapted from Practical Unix and Programming Hunter College Copyright 2006 2009 Stewart Weiss Back to shell scripts Now that you've learned a few commands and can edit files,

More information

What is PHP? [1] Figure 1 [1]

What is PHP? [1] Figure 1 [1] PHP What is PHP? [1] PHP is an acronym for "PHP: Hypertext Preprocessor" PHP is a widely-used, open source scripting language PHP scripts are executed on the server PHP is free to download and use Figure

More information

Review of Fundamentals

Review of Fundamentals Review of Fundamentals 1 The shell vi General shell review 2 http://teaching.idallen.com/cst8207/14f/notes/120_shell_basics.html The shell is a program that is executed for us automatically when we log

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

IT 374 C# and Applications/ IT695 C# Data Structures

IT 374 C# and Applications/ IT695 C# Data Structures IT 374 C# and Applications/ IT695 C# Data Structures Module 2.1: Introduction to C# App Programming Xianrong (Shawn) Zheng Spring 2017 1 Outline Introduction Creating a Simple App String Interpolation

More information

Bash scripting Tutorial. Hello World Bash Shell Script. Super User Programming & Scripting 22 March 2013

Bash scripting Tutorial. Hello World Bash Shell Script. Super User Programming & Scripting 22 March 2013 Bash scripting Tutorial Super User Programming & Scripting 22 March 2013 Hello World Bash Shell Script First you need to find out where is your bash interpreter located. Enter the following into your command

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information