A Few More Functions. One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. –no interpolation.

Slides:



Advertisements
Similar presentations
Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
Advertisements

1/12 Steven Leung Very Basic Perl Tricks A Few Ground Rules File I/O and Formatting Operators, Flow Control Statements Regular Expression Subroutines Hash.
Programming Perls* Objective: To introduce students to the perl language. –Perl is a language for getting your job done. –Making Easy Things Easy & Hard.
4.1 Reading and writing files. 4.2 Open a file for reading, and link it to a filehandle: open(IN, "
Programming and Perl for Bioinformatics Part III.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
COS 381 Day 19. Agenda Questions?? Resources Source Code Available for examples in Text Book in Blackboard
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
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.
Scalar Variables Start the file with: #! /usr/bin/perl –w No spaces or newlines before the the #! “#!” is sometimes called a “shebang”. It is a signal.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Sorting. Simple Sorting As you are probably aware, there are many different sorting algorithms: selection sort, insertion sort, bubble sort, heap sort,
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
I/O while ($line= ){ #remove new line char \n chomp($line); if($line eq “quit”){ exit(1); } while ( ){ #remove new line char \n chomp($_); if($_ eq “quit”){
Subroutines. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We’ll just say Subroutines. –“Functions” generally means built-in.
Shell Script Examples.
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
Introduction to Perl Practical Extraction and Report Language or Pathologically Eclectic Rubbish Lister or …
1 Perl Perl basics Perl Elements Arrays and Hashes Control statements Operators OOP in Perl.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
An Introduction to Unix Shell Scripting
The UNIX Shell. The Shell Program that constantly runs at terminal after a user has logged in. Prompts the user and waits for user input. Interprets command.
Control Structures. Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block.
4 1 Array and Hash Variables CGI/Perl Programming By Diane Zak.
Linux Operations and Administration
UNIX Shell Script (1) Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
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.
Perl Practical(?)‏ Extraction and Report Language.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Introduction to Perl Yupu Liang cbio at MSKCC
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
Introduction to Programming the WWW I CMSC Winter 2003.
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
5 1 Data Files CGI/Perl Programming By Diane Zak.
LIN Unix Lecture 5 Unix Shell Scripts. LIN Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Perl Chapter 5 Hashes. Outside of world of Perl, know as associative arrays Also called hash tables Perl one of few languages that has hashes built-in.
1 More Perl Strings References Complex data structures –Multidimensional arrays Subprograms Perl OOP –Methods –Constructors and Instances –Inheritance.
Perl Chapter 6 Functions. Subprograms In Perl, all subprograms are functions – returns 0 or 1 value – although may have “side-effects” optional function.
CPTG286K Programming - Perl Chapter 4: Control Structures.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
Random Bits of Perl None of this stuff is worthy of it’s own lecture, but it’s all a bunch of things you should learn to use Perl well.
Getting started in Perl: Intro to Perl for programmers Matthew Heusser – xndev.com - Presented to the West Michigan Perl User’s Group.
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.
More Perl Data Types Scalar: it may be a number, a character string, or a reference to another data type. -the sigil $ is used to denote a scalar(or reference)
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Interpolation Variable Interpolation, Backslash Interpolation.
Intro to Object Oriented Perl Packages, Modules, Classes.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
2000 Copyrights, Danielle S. Lahmani Foreach example = ( 3, 5, 7, 9) foreach $one ) { $one*=3; } is now (9,15,21,27)
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Camel –perldoc perlop Many operators have numeric and string version –remember Perl will.
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Built-In Functions. Notations For each function, I will give its name and prototype. –prototype = number and type of arguments ARRAY means an actual named.
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.
Perl Variables: Hash Web Programming.
Context.
Subroutines.
Introduction to Bash Programming, part 3
Presentation transcript:

A Few More Functions

One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. –no interpolation = qw/cat dog bird  ('cat', 'dog', 'bird', 'mouse'); As with q//, qq//, qx//, m//, and s///, you may choose any non-alphanumeric character for the delimiter.

map (EXPR|BLOCK) LIST evaluate EXPR (or BLOCK) for each value of LIST. Set $_ to each value of LIST, much like a foreach loop Returns a list of all results of the expression = map {split(' ', –for each element (alias the element to $_), run split(' ', $_), push results Equivalent: foreach { split(' ', $_); }

More map examples = qw/morning afternoon night/; = map  ("Good morning", "Good afternoon", "Good night") = (1..5); = map {$_  (2, 4, 6, 8, 10); If you use a block, there is no comma separating the args. If you use an expression, there is.

grep (EXPR|BLOCK) LIST Similar concept to map (and same syntax) returns a list of all members of the original list for which expression was true. –(map returns list of all return values of each evaluation) Pick out elements you want to = grep –picks out all lines beginning with comments –Assigns $_ to each member then evaluates the pattern match. If pattern match is true, $_ is = grep { $_ % 2 == = grep { 9 < length

grep equivalence = grep for if (/^\s*#/){ $_; } }

each Pick out keys and values from a hash. In scalar context, just gets the next key: while (my $key = each %hash){...} –foreach my $key (keys %hash){...} In list context, gets the next key and value of the hash. while (my ($key,$val)= each %hash) {...} –foreach my $key (keys %hash) { my $val = $hash{$key};... } If your list contains more than 2 variables, others get assigned to undef Will return key/val in same "random" order as keys() and values()

glob EXPR returns EXPR after it has passed through Unix filename expansion. –as evaluated by the csh shell In Unix, ~ is a wild card that means "home directory of this user" –ie, my home directory is ~lallip/ Other wildcards: –*  0 or more of any character –?  exactly one of any character. Fails: opendir my $dh, '~lallip'; Works: opendir my $dh, glob '~lallip';

glob returns In list context, returns all files/directories that fit the pattern of the wildcard expansion. = glob ('*.pl'); –gets a list of all files with a.pl extension in the current directory. In scalar context, returns the "next" file/directory that fits the pattern. After last entry, will return undef before returning first entry again. while (my $file = glob ('*.txt')){ print "file = $file\n"; } Special operator uses glob internally –while (my $file = ) { … }

eval EXPR evaluate perl code. Code is parsed and executed at run-time. This is considered highly dangerous by some people, and causes some to warn people away from eval altogether. my $x; my $foo = q{$x = 'hello';}; eval $foo; #$x now set to 'hello'

eval BLOCK evaluate perl code Code is parsed at compile time This is perl's method of exception handling. Fatal errors are trapped, errors stored in eval { $x = $y / $z; }; warn "Exception caught: if Both perl errors, and your own die() calls are caught.

undef & defined undef undefines its argument Also returns undefined value. –$foo = undef; #works undef $foo; #preferred = undef; #doesn't work!! = (); #preferred undef can be used to throw away unneeded values: ($foo, undef, $bar) = fctn(); defined returns true if argument is not undef. Returns false otherwise. my ($foo, $bar) = (5); print "Foo is undef\n" if !defined $foo; print "Bar is undef\n" if !defined $bar;

delete & exists delete removes a key/value pair from a hash my %foo = (one=>1, junk=>-999, two=>2); delete $foo{junk}; %foo  (one=>1, two=>2); –(contrast with undef $foo{junk} …) Can be used with arrays, but doesn't do the same: = ('a'..'e'); delete  ('a', 'b', undef, 'd', 'e') –will shrink array if the deleted element is last exists returns true if the key exists in the hash: print "%foo has a value at 'one'\n" if exists $foo{one}; –(contrast with defined $foo{one} )

status of hash elements hash key exists  value may be false, may be undef hash value defined  key exists, value may be false. hash value true  value is defined, key exists. if (exists $hash{$key}){ if (defined $hash{$key}){ if ($hash{$key}){ print "$hash{$key} is true\n"; } else { print "$hash{$key} is false\n"; } } else { print "$key exists, value undef\n"; } } else { print "$key does not exist in hash\n"; }

our 'declares' a global variable to be used within the smallest enclosing block. Within the block, the global variable does not need to be fully qualified. Obviously, only has any meaning if strict is being used. our $foo; –Can now use $main::foo just by saying $foo. Still no reason to do this - file-scoped lexicals are all you need. –until Object Oriented Perl