Perl Subroutines User Input Perl on linux Forks and Pipes.

Slides:



Advertisements
Similar presentations
Lab 9 CIS 370 Umass Dartmouth.  A pipe is typically used as a one-way communications channel which couples one related process to another.  UNIX deals.
Advertisements

1 CS345 Operating Systems Φροντιστήριο Άσκησης 1.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Computer Programming for Biologists Class 9 Dec 4 th, 2014 Karsten Hokamp
COMP234 Perl Printing Special Quotes File Handling.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
1 Processes and Pipes COS 217 Professor Jennifer Rexford.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Perl Functions Software Tools. Slide 2 Defining a Function l A user-defined function or subroutine is defined in Perl as follows: sub subname{ statement1;
Introduction to Perl. How to run perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Your program/script.
Scripting Languages Perl Chapter #4 Subroutines. Writing your own Functions Functions is a programming language serve tow purposes: –They allow you to.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
Introduction to Perl Software Tools. Slide 2 Introduction to Perl l Perl is a scripting language that makes manipulation of text, files, and processes.
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
 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.
A First Program Using C#
UNIX command line. In this module you will learn: What is the computer shell What is the command line interface (or Terminal) What is the filesystem tree.
Introduction to Shell Script Programming
Introduction to Perl Practical Extraction and Report Language or Pathologically Eclectic Rubbish Lister or …
Introduction to Perl & BioPerl Dr G. P. S. Raghava Bioinformatics Centre Bioinformatics Centre IMTECH, Chandigarh Web:
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
– Introduction to the Shell 10/1/2015 Introduction to the Shell – Session Introduction to the Shell – Session 2 · Permissions · Users.
An Introduction to Unix Shell Scripting
1 Functions 1 Parameter, 1 Return-Value 1. The problem 2. Recall the layout 3. Create the definition 4. "Flow" of data 5. Testing 6. Projects 1 and 2.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
1 Week 2 The Crunchy Shell to the Soft and Chewy Kernel… Sarah Diesburg 8/3/2010 COP4610 / CGS5765.
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.
Mel & Hot Keys Review. What’s MEL?  Maya Embedded Language  Most of Maya's interface is built using MEL commands and scripts.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Bioinformatics Introduction to Perl. Introduction What is Perl Basic concepts in Perl syntax: – variables, strings, – Use of strict (explicit variables)
CS162B: Pipes Jacob T. Chan. Pipes  These allow output of one process to be the input of another process  One of the oldest and most basic forms of.
CPS120: Introduction to Computer Science Decision Making in Programs.
Introduction to Perl Yupu Liang cbio at MSKCC
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
JavaScript, Fourth Edition
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Operating Systems Process Creation
Introduction to Programming Using C An Introduction to Operating Systems.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
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.
Process Management Azzam Mourad COEN 346.
Week Four Agenda Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems Upcoming deadlines.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Bioinformatics Introduction to Perl. Introduction What is Perl Basic concepts in Perl syntax: – variables, strings, – Use of strict (explicit variables)
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
CS241 Systems Programming Discussion Section Week 2 Original slides by: Stephen Kloder.
 Prepared by: Eng. Maryam Adel Abdel-Hady
 Prepared by: Eng. Maryam Adel Abdel-Hady
Linux Administration Working with the BASH Shell.
 Prepared by: Eng. Maryam Adel Abdel-Hady
Week Four Agenda Announcements Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems.
1 Intro to the Shell with Fork, Exec, Wait Sarah Diesburg Operating Systems CS 3430.
Lecture 5 Page 1 CS 111 Online Process Creation Processes get created (and destroyed) all the time in a typical computer Some by explicit user command.
Development Environment
Programming Basics Web Programming.
Process Creation Processes get created (and destroyed) all the time in a typical computer Some by explicit user command Some by invocation from other running.
The Linux Operating System
Lesson 2. Control structures File IO - reading and writing Subroutines
Linux Shell Script Programming
Functions continued.
Presentation transcript:

Perl Subroutines User Input Perl on linux Forks and Pipes

Subroutines

Subroutines are named code blocks Used to: – shorten code blocks in larger programs –Avoid repeating code blocks re-useable code –Implement “abstraction” your own “high level” language Sometimes called “user defined functions”

Subroutines Shorten code blocks in larger programs Miller Number (7 +or- 2) – People seem to be able to hold that many things in memory –Registers? So we want to break modules down into that many pieces

Subroutines On the decomposition of programs into modules – Encapsulate design decisions Minimise connections between modules Disciplined data flow –No global variables

Subroutines Subroutines are declared –sub mysub {block} Not run until "called" Subroutines are functions –they return a value Actually a list –return value is value of last expression evaluated –or values referenced in "return" statement

Subroutines Subroutines can be run by referencing their name like a function –mysub(); –mysub; –&mysub; & before the subroutine name may be required if the reference to the subroutine precedes its definition in the source file If you like to define subs after referencing them, precede the reference with &

Getting data in and out Variables in perl are global by default But you want to pass data to a subroutine as a parameter – not as a global variable Subroutines receive parameters just like main program – in an array Programs get command line parameters array Subroutines get values array

Example sub adder { return $_[0] + $_[1]; } $sum = adder(5,8); print adder(1,2),"\n"; print "$sum\n"; Result: cmblap:~ # perl test.pl 3 13 cmblap:~ #

Private Variables Example sub adder { $sum= $_[0] + $_[1]; return $sum; } $sum = adder(5,8); print adder(1,2),"\n"; print "$sum\n"; Result cmblap:~ # perl test.pl 3

Private Variables sub adder { my $sum; $sum= $_[0] + $_[1]; return $sum; } $sum = adder(5,8); print adder(1,2),"\n"; print "$sum\n"; Result cmblap:~ # perl test.pl 3 13

Data Flow Always pass data to subroutines as parameters Always return information as a return value, or modified parameters –Return value is better Make reference only to variables declared private (using “my $variable_name” etc) in the subroutine

User Input

$inputline = ; This tells Perl to read a line of text from standard input (represented by STDIN) and assign this value to the variable $inputline. A line of text is s text string terminated by a line terminator Standard input is the keyboard by default

User Input Sample program input.pl $input= ; print "Here is what I typed: $input"; Sample output: cmblap:~ # perl input.pl some stuff Here is what I typed: some stuff cmblap:~ #

User Input A slight change: $input= ; print "Here: $input is what I typed "; New Output: cmblap:~ # perl input.pl some stuff Here: some stuff is what I typed cmblap:~ #

User Input Another slight change: $input= ; chomp $input; print "Here: $input is what I typed: \n"; Output cmblap:~ # perl input.pl more stuff Here: more stuff is what I typed: cmblap:~ #

chomp The chomp function removes a trailing newline from a variable. chop is similar but removes the last character no matter what it is. chomp is used to clean up input

Perl on Linux

Perl on linux May be many more packages Especially if the windows perl uses PPM –ActivePerl Sometimes newer versions Command line switches slightly different Shabang line different

Running perl Open a command line window –Sometimes called terminal window in linux cmblap:~ # perl -e 'print "Hello World\n" ' Hello World cmblap:~ #

Editing Perl scripts Kali linux doesn't come with a good editor for perl but gedit can be installed with apt- get install gedit then gedit test.pl Syntax highlighting makes it a little easier to know if you have committed errors

shabang At command prompt type whereis perl –to find out path to perl enterpreter Should say /usr/bin/perl Put shabang line: #!/usr/bin/perl -w at the start of your program

Make your program executable In linux files to be executed need to have executable permission chmod +x myfile.pl makes myfile.pl executable Then you can run it like this:./myfile.pl –“./” means current directory Or you can just type perl myfile.pl

Saving Your Program No “H” drive in linux –To access your “H” drive use the web interface Program output can be saved to a file using redirection./myprogram.pl > some-file.txt Runs myprogram.pl and saves the output in some-file.txt Flash drive will be a subdirectory of /media

Saving Command Line History Highlight the text you want to save Move to editor Middle button pastes highlighted text into the editor

Forking child processes

Forks Forking creates a new sub-process with the process that did the forking as the parent process In perl, the sub-process is identical to the parent and begins execution at the same point File descriptors are shared, and the child gets a copy of everything else

The fork Function fork Takes no parameters Returns –To the parent: The pid (process id) of the child Or Undef if the fork failed –To the child Zero

Waiting on your children The wait function waits for a child process to die Returns the pid of the child Or -1 if there are no children If a forking process doesn't wait for the children to die they may become zombies

Example if ($pid = fork) { &parent ($pid); # pass child pid to # parent subroutine waitpid($pid,0); # wait till child dies } elsif (defined $pid) { &child; # do child subroutine } else { die "cannot fork: $!"; }

pid Parent receives pid of child as return value of fork function waitpid $pid can be used to wait for a particular child's death (in case you have many) Built-in variable $$ contains your own pid

Talking to your children Pipes

pipe function The pipe function creates a pipe and two file handles Example: pipe(READER, WRITER); The first file handle can be used to read data from the pipe The second can be used to write to the pipe Create the pipe before forking so parent and child can share the pipe

Unidirectional / Bidirectional pipes are bidirectional, so processes could both read and write to the same pipe This can lead to problems: –Reads are blocking, so if both processes read the pipe at once, both will block and nothing will ever happen –Read will return with UNDEF (like end of file) when all writers are closed, but reader must close its own write file handle first or this will never happen Easier to be unidirectional by closing the unused file handle

Writing to the pipe print WRITER "$msg\n"; A problem: pipe IO is block buffered Reader may not see the message for a while –Maybe not until the writer closes the pipe –Fix this by turning on autoflush autoflush WRITER 1; or select WRITER; #WRITER now default FH $| = 1; select STDOUT;

Reading from a pipe while (my $line = ) { print "pid $$ received: $line"; } Just like reading a file Blocking read Reads to next line terminator $line will be UNDEF when writer closes the pipe, or terminates

Today's lab Create a pipe Fork a sub-process Parent gets a message from the user, sends it to the child Child gets the message, prints it to the screen Repeat until user doesn't enter a message Simple, (really)