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.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Input from STDIN STDIN, standard input, comes from the keyboard. STDIN can also be used with file re-direction from the command line. For instance, if.
ISBN Regular expressions Mastering Regular Expressions by Jeffrey E. F. Friedl –(on reserve.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Bash Shell Scripting 10 Second Guide Common environment variables PATH - Sets the search path for any executable command. Similar to the PATH variable.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Slide 6a-1 CHAPTER 6 Matching Patterns: Using Regular expressions to match patterns.
Lecture 7: Perl pattern handling features. Pattern Matching Recall =~ is the pattern matching operator A first simple match example print “An methionine.
Computer Programming for Biologists Class 5 Nov 20 st, 2014 Karsten Hokamp
Week 7 Working with the BASH Shell. Objectives  Redirect the input and output of a command  Identify and manipulate common shell environment variables.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Program A computer program (also software, or just a program) is a sequence of instructions written in a sequence to perform a specified task with a computer.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Perl and Regular Expressions Regular Expressions are available as part of the programming languages Java, JScript, Visual Basic and VBScript, JavaScript,
Linux+ Guide to Linux Certification, Third Edition
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Agenda Regular Expressions (Appendix A in Text) –Definition / Purpose –Commands that Use Regular Expressions –Using Regular Expressions –Using the Replacement.
Week 1 Algorithmization and Programming Languages.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Control Structures By Shyam Gurram. Control Structure In this chapter we have two different types of structures. Conditional Structure Iterative Control.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
When you read a sentence, your mind breaks it into tokens—individual words and punctuation marks that convey meaning. Compilers also perform tokenization.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Perl II Part III: Motifs and Loops. Objectives Search for motifs in DNA or Proteins Interact with users at the keyboard Write data to files Use loops.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
Introduction to Computer Programming
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Copyright © Curt Hill Regular Expressions Providing a Search Pattern.
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Standard Types and Regular Expressions CS 480/680 – Comparative Languages.
Prof. Alfred J Bird, Ph.D., NBCT Door Code for IT441 Students.
Computer Programming for Biologists Class 4 Nov 14 th, 2014 Karsten Hokamp
Introduction to Programming the WWW I CMSC Winter 2004 Lecture 13.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Part 4 Arrays: Stacks foreach command Regular expressions: String structure analysis and substrings extractions and substitutions Command line arguments:
ORAFACT Text Processing. ORAFACT Searching Inside Files grep - searches for patterns within files grep [options] [[-e] pattern] filename [...] -n shows.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
Variable Variables A variable variable has as its value the name of another variable without $ prefix E.g., if we have $addr, might have a statement $tmp.
-Joseph Beberman *Some slides are inspired by a PowerPoint presentation used by professor Seikyung Jung, which was derived from Charlie Wiseman.
The Scripting Programming Language
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
Perl Subroutines User Input Perl on linux Forks and Pipes.
1 UNIX Operating Systems II Part 2: Shell Scripting Instructor: Stan Isaacs.
Shell Scripting September 27, 2004 Class Meeting 6, Part II * Notes adapted by Lenwood Heath from previous work by other members of the CS faculty at Virginia.
Linux Administration Working with the BASH Shell.
Input from STDIN STDIN, standard input, comes from the keyboard.
Shell Scripting March 1st, 2004 Class Meeting 7.
Regular Expressions and perl
Lecture 9 Shell Programming – Command substitution
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Perl Variables: Array Web Programming.
Introduction to Computer Science
CIS 136 Building Mobile Apps
Presentation transcript:

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)

Another = qw ( = will contain ( ) How do sort = qw ( = sort {$a will contain ( )

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”, = splice 1, 2); contains the elements removed

File Handling

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.

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.

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

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;

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

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

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

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

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

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;

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 { print “$_ \n”; }

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.

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

$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

Control Structures

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.

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.

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.

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

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

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

Sort the elements in numerical = qw ( = sort {$a Write a Perl program segment to sort an array in the descending = sort =

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.

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 ;

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);

String Functions

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 { print “$_\n”; } The first parameter to ‘split’ is a regular expression that specifies what to split on. The second specifies what to split.

Another example: $_= “sateesh ($name, $ , $phone) = split / /, $_; By default, ‘split’ breaks a string using space as delimiter.

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;

Regular Expressions

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.

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

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.

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.

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

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.

Matching

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.

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.

$string = “Good day”; if ($string =~ { print “Match successful \n"; } if ($string =~ m[day[ ) { print “Match successful \n"; } Both forms are equivalent. The character following ‘m’ is the delimiter.

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

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

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

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

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

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

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

Substitution

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.

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

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

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.

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

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

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

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

Some Special Variables

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

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

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

Data structures in Perl

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

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 ); print

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'};