Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings.

Similar presentations


Presentation on theme: "Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings."— Presentation transcript:

1 Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings. @colors = qw (red blue green black); @sort_colors = sort @colors # Array @sort_colors is (black blue green red)

2 Another example @num = qw (10 2 5 22 7 15); @new = sort @num; # @new will contain (10 15 2 22 5 7) How do sort numerically? @num = qw (10 2 5 22 7 15); @new = sort {$a $b} @num; # @new will contain (2 5 7 10 15 22)

3 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 remove. @colors = (“red”, “green”, “blue”, “black”); @middle = splice (@colors, 1, 2); # @middle contains the elements removed

4 File Handling

5 Interacting with the user Read from the keyboard (standard input). Use the file handle. Very simple to use. print “Enter your name: ”; $name = ; # Read from keyboard print “Good morning, $name. \n”; $name also contains the newline character. Need to chop it off.

6 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 = ); # 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.

7 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 = ); # Read from keyboard and chomp newline print “Good morning, $name. \n”;

8 File Operations Opening a file The ‘open’ command opens a file and returns a file handle. For standard input, we have a predefined handle. $fname = “/home/isg/report.txt”; while ( ) { print “Line number $. : $_”; } open XYZ, $fname;

9 Checking the error code : $fname = “/home/isg/report.txt”; open XYZ, $fname or die “Error in open: $!”; while ( ) { print “Line number $. : $_”; } $. returns the line number (starting at 1) $_ returns the contents of last match $! returns the error code/message

10 Reading from a file: The last example also illustrates file reading. The angle brackets ( ) are the line input operators. The data read goes into $_

11 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”; }

12 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”; }

13 Closing a file: where XYZ is the file handle of the file being closed. close XYZ ;

14 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 ( ) { print; } close IN;

15 Command Line Arguments Perl uses a special array called @ARGV. 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 then @ARGV will be (red blue green). Printing the command line arguments: foreach (@ARGV) { print “$_ \n”; }

16 Standard File Handles Read from standard input (keyboard). Print to standard output (screen). For outputting error messages. Reads the names of the files from the command line and opens them all.

17 @ARGV array contains the text after the program’s name in command line. 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,namely, An example is shown.

18 $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

19 Control Structures

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

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

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

23 if.. else General syntax: if (test expression) { # if TRUE, do this } else { # if FALSE, do this }

24 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

25 elseif Example: print “Enter your id: ”; chomp ($name = ); 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”; }

26 Sort the elements in numerical order? @num = qw (10 2 5 22 7 15); @new = sort {$a $b} @num; Write a Perl program segment to sort an array in the descending order. @new = sort {$a $b} @num; @new = reverse @new;

27 What is the difference between the functions ‘chop’ and ‘chomp’? “chop” removes the last character in a string. “chomp” does the same, but only if the last character is the newline character. Write a Perl program segment to read a textfile “input.txt”, and generate as output another file “out.txt”, where a line number precedes all the lines.

28 open INP, “input.txt” or die “Error in open: $!”; open OUT, “>$out.txt” or die “Error in write:$!”; while ( ) { print OUT “$. : $_”; } close INP; close OUT ;

29 What is the significance of the file handle ? It reads the names of files from the command line and opens them all (reads line by line). How can you exit a loop in Perl based on some condition? Using the “last” keyword. last if (i > 10);

30 String Functions

31 The Split Function ‘ split’ is used to split a string into multiple pieces using a delimiter, and create a list out of it. $_=‘Red:Blue:Green:White:255'; @details = 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.

32 Another example: $_= “sateesh satteesh@gmail.com 283493”;satteesh@gmail.com ($name, $email, $phone) = split / /, $_; By default, ‘split’ breaks a string using space as delimiter.

33 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, $w3, @abc, $x4, $x5;

34 Regular Expressions

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

36 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”; }

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

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

39 Another Simple Example $_ = “Welcome to SRI NIDHI, students”; if (/SRI NIDHI/) { print “’SRI NIDHI’ is present in the string\n”; { if (/toSRI NIDHI/) { print “This will not match\n”; }

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

41 Matching

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

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

44 $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.

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

46 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"; }

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

48 $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"; }

49 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

50 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”?

51 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?$/;

52 Substitution

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

54 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$/ /;

55 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

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

57 Examples $string = “Ram and Shyam are honest"; $string =~ /^(\w+)/; print $1, "\n"; # prints “Ra\n” $string =~ /(\w+)$/; print $1, "\n"; # prints “st\n”

58 $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/;

59 Example 1 validating user input print “Enter age (or 'q' to quit): "; chomp (my $age = ); exit if ($age =~ /^q$/i); if ($age =~ /\D/) { print "$age is a non-number!\n"; }

60 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 = ) { chomp $line; next if ($line =~ /^\s*$/ or $line =~ /^\s*#/); my ($name, $age) = split /\s+/, $line; print “The age of $name is $age. \n"; }

61 Some Special Variables

62 $&, $` 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.

63 Example: $_ = 'abcdefghi'; /def/; print "$\`:$&:$'\n"; # prints abc:def:ghi

64 So actually …. S` represents pre match $& represents present match $’ represents post match

65 Data structures in Perl

66 The following example defines a sample perl array of arrays. @tgs = ( ['article series', 'sed & awk', 'troubleshooting', 'vim', 'bash'], ['ebooks', 'linux 101', 'vim 101', 'nagios core', 'bash 101' ] );

67 To access a single element, for example, to Access 2nd element from the 1st array, do the following: $tgs[0][1]; Access all the elements one by one as shown below. foreach ( @tgs ); print “@$_\n"

68 Perl Hash of Hashes %tags = ( 'articles' => { 'vim' => '20 awesome articles posted', 'awk' => '9 awesome articles posted', 'sed' => '10 awesome articles posted' }, 'ebooks' => { 'linux 101' => 'Practical Examples to Build a Strong Foundation in Linux', 'nagios core' => 'Monitor Everything, Be Proactive, and Sleep Well' } ); To access a single element from hash, do the following. print $tags{'ebooks'}{'linux 101'};


Download ppt "Sort the Elements of an Array Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings."

Similar presentations


Ads by Google