A Simple Perl Script
|
|
|
- Ellen Copeland
- 9 years ago
- Views:
Transcription
1 Perl
2 What is Perl? Practical Extraction and Report Language Scripting language created by Larry Wall in the mid-80s Functionality and speed somewhere between low-level languages (like C) and high-level ones (like shell ) Influence from awk, sed, and C Shell Easy to write (after you learn it), but sometimes hard to read Widely used in CGI scripting
3 A Simple Perl Script hello: #!/usr/bin/perl -w print Hello, world!\n ; turns on warnings $ chmod a+x hello $./hello Hello, world! $ perl -e print Hello, world!\n Hello, world!
4 Data Types Type of variable determined by special leading character %foo &foo scalar list hash function Data types have separate name spaces
5 Scalars Can be numbers $num = 100; $num = ; # integer # floating-point $num = -1.3e38; Can be strings $str = good morning ; $str = good evening\n ; $str = one\ttwo ; Backslash escapes and variable names are interpreted inside double quotes No boolean data type: 0 or means false! negates boolean value
6 Special Scalar Variables $0 $_ $$ $? $! $/ $. undef Name of script Default variable Current PID Status of last pipe or system call System error message Input record separator Input record number Acts like 0 or empty string
7 Operators Numeric: + - * / % ** String concatenation:. $state = New. York ; # NewYork String repetition: x print bla x 3; # blablabla Binary assignments: $val = 2; $val *= 3; # $val is 6 $state.= City ; # NewYorkCity
8 Comparison Operators Comparison Equal Not Equal Greater than Less than or equal to Greater than or equal to Numeric ==!= < > >= String eq ne lt le ge
9 undef and defined $f = 1; while ($n < 10) { } # $n is undef at 1st iteration $f *= ++$n; Use defined to check if a value is undef if (defined($val)) { }
10 Lists and Arrays List: ordered collection of scalars Array: Variable containing a list Each element is a scalar variable Indices are integers starting at 0
11 Array/List Knicks, Nets, Lakers ); print $teams[0]; # print Knicks $teams[3]= Celtics ; # add new = (); # empty = (1..100); # list of = ($x, $y*6); ($a, $b) = ( apple, orange ); ($a, $b) = ($b, $a); # swap $a
12 More About Arrays and Lists Quoted words - = qw/ earth mars jupiter = qw{ earth mars jupiter }; Last element s index: $#planets Not the same as number of elements in array! Last element: $planets[-1]
13 Scalar and List = qw< red green blue >; Array as string: print My favorite colors ; Prints My favorite colors are red green blue Array in scalar context returns the number of elements in the list $num + 5; # $num gets 8 Scalar expression in list = 88; # one element list (88)
14 pop and push push and pop: arrays used as stacks push adds element to end of = qw# red green blue #; push(@colors, yellow = (@colors, yellow # same as pop removes last element of array and returns it $lastcolor = pop(@colors);
15 shift and unshift shift and unshift: similar to push and pop on the left side of an array unshift adds elements to the = qw# red green blue ; orange ; First element is now orange shift removes element from beginning $c = shift(@colors); # $c gets orange
16 sort and reverse reverse returns list with elements in reverse = qw# NY NJ CT = reverse(@list1); # (CT,NJ,NY) sort returns list with elements in ASCII- sorted = qw/ tues wed thurs = sort(@day); = sort 1..10; # reverse and sort do not modify their arguments reverse in scalar context flip characters in string $flipped = reverse( abc ); # gets cba
17 Iterate over a List foreach loops throught a list of = qw# Knicks Nets Lakers #; foreach $team (@teams) { print $team win\n ; } Value of control variable is restored at the end of the loop $_ is the default foreach (@teams) { } $_.= win\n ; print; # print $_
18 Hashes Associative arrays - indexed by strings (keys) $cap{ Hawaii } = Honolulu ; %cap = ( New York, Albany, New Jersey, Trenton, Delaware, Dover ); Can use => (the big arrow or comma arrow) in place of, %cap = ( New York => Albany, New Jersey => Trenton, Delaware => Dover );
19 Hash Element Access $hash{$key} print $cap{ New York }; print $cap{ New. York }; Unwinding the = %cap; Gets unordered list of key-value pairs Assigning one hash to another %cap2 = %cap; %rev_cap = reverse %cap; print $rev_cap{ Trenton }; # New Jersey
20 Hash Functions keys returns a list of = keys %cap; values returns a list of = values %cap; Use each to iterate over all (key, value) pairs while ( ($state, $city) = each %cap ) { print Capital of $state is $city\n ; }
21 Subroutines sub myfunc { } $name= Jane ; sub print_hello { } print Hello $name\n ; # global $name &print_hello; print_hello; hello(); # print Hello Jane # print Hello Jane # print Hello Jane
22 Arguments Parameters are assigned to the special Individual parameter can be accessed as $_[0], $_[1], sub sum { my $x; # private variable $x foreach (@_) { # iterate over params $x += $_; } return $x; } $n = &sum(3, 10, 22); # n gets 35
23 More on Parameter Passing Any number of scalars, lists, and hashes can be passed to a subroutine Lists and hashes are flattened %z); Inside func: $_[0] is $x $_[1] is $y[0] $_[2] is $y[1], etc. The scalars are implicit aliases (not copies) of the ones passed, i.e. changing the values of $_[0], etc. changes the original variables
24 Return Values The return value of a subroutine is the last expression evaluated, or the value returned by the return operator sub myfunc { my $x = 1; $x + 2; #returns 3 } sub myfunc { my $x = 1; return $x + 2; } Can also return a list: If return is used without an expression (failure), undef or () is returned depending on context
25 Lexical Variables Variables can be scoped to the enclosing block with the my operator sub myfunc { my $x; my($a, $b) # copy params } Can be used in any block, such as an if block or while block Without enclosing block, the scope is the source file
26 Another Subroutine = (1, 2, 3); $num = = dec_by_one(@nums, $num); 1, 2, 3) # (@nums,$num)=(1, 2, 3, 4) dec_by_1(@nums, $num); # (@nums,$num)=(0, 1, 2, 3) sub dec_by_one { for my $n (@ret) { $n-- } } sub dec_by_1 { for (@_) { $_-- } } # make a copy
27 Reading from STDIN STDIN is the builtin filehandle to the standard input Use the line input operator around a file handle to read from it $line = <STDIN>; # read next line chomp($line); chomp removes trailing string that corresponds to the value of $/ - usually the newline character
28 Reading from STDIN example while (<STDIN>) { chomp; print Line $. ==> $_\n ; } Line 1 ==> [Contents of line 1] Line 2 ==> [Contents of line 2]
29 < > The diamond operator < > makes Perl programs work like standard Unix utilities Lines are read from list of files given as command line arguments while (<>) { chomp; print Line $. from $ARGV is $_\n ; }./myprog file1 file2 - Read from file1, then file2, then standard input $ARGV is the current filename
30 Filehandles Use open to open a file for reading/writing open LOG, syslog ; # read open LOG, <syslog ; open LOG, >syslog ; open LOG, >>syslog ; # read # write # append Close a filehandle after using the file close LOG;
31 Errors When a fatal error is encountered, use die to print out error message and exit program die Something bad happened\n if.; Always check return value of open open LOG, >>syslog or die Cannot open log: $! ; For non-fatal errors, use warn instead warn Temperature is below 0! if $temp < 0;
32 Reading from a File open MSG, /var/log/messages or die Cannot open messages: $!\n ; while (<MSG>) { chomp; # do something with $_ } close MSG;
33 Writing to a File open LOG, >/tmp/log or die Cannot create log: $! ; print LOG Some log messages \n printf LOG %d entries processed.\n, $num; close LOG; no comma after filehandle
34 Manipulating Files and Dirs unlink removes files unlink file1, file2 or warn failed to remove file: $! ; rename renames a file rename file1, file2 ; link creates a new (hard) link link file1, file2 or warn can t create link: $! ; symlink creates a soft link link file1, file2 or warn ;
35 Manipulating Files and Dirs cont. mkdir create directory mkdir mydir, 0755 or warn Cannot create mydir: $! ; rmdir remove empty directories rmdir dir1, dir2, dir3 ; chmod modifies permissions on a file or directory chmod 0600, file1, file2 ;
36 if - elsif - else if elsif else if ( $x > 0 ) { print x is positive\n ; } elsif ( $x < 0 ) { print x is negative\n ; } else { print x is zero\n ; }
37 while and until while ($x < 100) { } $y += $x++; until is like the opposite of while until ($x >= 100) { } $y += $x++;
38 for for (init; test; incr) { } # sum of squares of 1 to 5 for ($i = 1; $i <= 5; $i++) { $sum += $i*$i; }
39 next next skips the remaining of the current iteration (like continue in C) # only print non-blank lines while (<>) { } if ( $_ eq \n ) { next; } else { print; }
40 last last exist the loop immediately (like break in C) # print up to first blank line while (<>) { if ( $_ eq \n ) { last; } else { print; } }
41 Logical AND/OR Logical AND : && if (($x > 0) && ($x < 10)) { } Logical OR : if ($x < 0) ($x > 0)) { } Both are short-circuit operators - the second expression is only evaluated if necessary
42 Regular Expressions Use EREs (egrep style) Plus the following character classes \w word character: [A-Za-z0-9_] \d digits: [0-9] \s whitespace: [\f\t\n\r ] \b word boundary \W, \D, \S, \B are complements of the corresponding classes above Can use \t to denote a tab
43 Backreferences Support backreferences Subexpressions are referred to using \1, \2, etc. in the RE and $1, $2, etc. outside the RE if (/^this (red blue green) (bat ball) is \1/) { } ($color, $object) = ($1, $2);
44 Matching Pattern match operator: /RE/ is a shortcut of m/re/ Returns true if there is a match Match against $_ be default Can also use m(re), m<re>, m!re!, etc. if (/^\/usr\/local\//) { } if (m%/usr/local/%) { } Case-insensitive match if (/new york/i) { };
45 Matching cont. To match an RE against something other than $_, use the binding operator =~ if ($s =~ /\bblah/i) { print Find blah! }!~ negates the match while (<STDIN>!~ /^#/) { } Variables are interpolated inside REs if (/^$word/) { }
46 Match Variables Special match variables $& : the section matched $` : the part before the matched section $ : the part after the matched section $string = "What the heck!"; $string =~ /\bt.*e/; print "($`) ($&) ($')\n"; (What ) (the he) (ck!)
47 Substitutions Sed-like search and replace with s/// s/red/blue/; $x =~ s/\w+$/$`/; Unlike m///, s/// modifies the variable Global replacement with /g s/(.)\1/$1/g; Transliteration operator: tr/// or y/// tr/a-z/a-z/;
48 RE Functions split string using RE (whitespace by = split /:/, ::ab:cde:f ; # gets (,, ab, cde, f ) join strings into one $str = join # gets --ab-cde-f grep something from a list Similar to UNIX grep, but not limited to using regular = Modifying elements in returned list actually modifies the elements in the original list
49 Running Another program Use the system function to run an external program With one argument, the shell is used to run the command Convenient when redirection is needed $status = system( cmd1 args > file ); To avoid the shell, pass system a list $status = die $prog exited abnormally: $? unless $status == 0;
50 Capturing Output If output from another program needs to be collected, use the backticks my $files = `ls *.c`; Collect all output lines into a single string = `ls *.c`; Each element is an output line The shell is invoked to run the command
51 Environment Variables Environment variables are stored in the special hash %ENV $ENV{ PATH } = /usr/local/bin:$env{ PATH } ;
52 Example: Union and Intersection = (1, 3, 5, 6, = (2, 4, 5, = (); %union = %isect = (); foreach $e (@a) { $union{$e} = 1} foreach $e (@b) { if ($union($e) ) { $isect{$e} = 1 } $union{$e} = 1; = keys = keys %isect;
53 Example: Union and Intersection = (1, 3, 5, 6, = (2, 4, 5, = (); %union = %isect = (); foreach $e { $union{$e}++ && $isect{$e}++; = keys = keys %isect;
54 Example: Word Frequency #!/usr/bin/perl -w # Read a list of words (one per line) and # print the frequency of each word use strict; my(@words, %count, $word); chomp(@words = <STDIN>); # read and chomp all lines foreach $word (@words) { $count{$word} += 1; } foreach $word (keys %count) { print $word was seen $count{$word} times.\n ; }
55 Good Ways to Learn Perl a2p Translates an awk program to Perl s2p Translates a sed script to Perl perldoc Online perl documentation $ perldoc perldoc <-- perldoc man page $ perldoc -f sort <-- Perl sort function man page $ perldoc CGI <-- CGI module man page
56 Modules Perl modules are libraries of reusable code with specific functionalities Standard modules are distributed with Perl, others can be obtained from Include modules in your program with use, e.g. use CGI incorporates the CGI module Each module has its own namespace
57 Perl CGI Module Interface for parsing and interpreting query strings passed to CGI scripts Methods for creating generating HTML Methods to handle errors in CGI scripts Two interfaces: procedural and objectoriented Need to ask for the procedural interface use CGI qw(:standard);
58 A (rather ugly) CGI Script #!/usr/bin/perl $size_of_form_info = $ENV{'CONTENT_LENGTH'}; read ($STDIN, $form_info, $size_of_form_info); # Split up each pair of key/value pairs foreach $pair (split (/&/, $form_info)) { # For each pair, split into $key and $value variables ($key, $value) = split (/=/, $pair); # Get rid of the pesky %xx encodings $key =~ s/%([\da-fa-f][\da-fa-f])/pack ("C", hex ($1))/eg; $value =~ s/%([\da-fa-f][\da-fa-f])/pack ("C", hex ($1))/eg; # Use $key as index for $parameters hash, $value as value $parameters{$key} = $value; } # Print out the obligatory content type line print "Content-type: text/plain\n\n"; # Tell the user what they said print "Your birthday is on ". $parameters{birthday}. ".\n";
59 A Perl CGI Script #!/usr/local/bin/perl -w use strict; use CGI qw(:standard); my $bday = param("birthday"); # Print headers (text/html is the default) print header(-type => 'text/html'); # Print <html>, <head>, <title>, <body> tags etc. print start_html( Birthday ); # Your HTML body print p("your birthday is $bday. ); # Print </body></html> print end_html(); Read the CGI Perl documentation (perldoc CGI)
60 Further Reading
Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl
First CGI Script and Perl Perl in a nutshell Prof. Rasley shebang line tells the operating system where the Perl interpreter is located necessary on UNIX comment line ignored by the Perl interpreter End
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting Language www.freebsdonline.com Copyright 2006-2008 www.freebsdonline.com 2008/01/29 This course is about Perl Programming
Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, 2008. 1 Introduction 1. 2 Invoking Shell Scripts 2
Unix Shell Scripts Norman Matloff July 30, 2008 Contents 1 Introduction 1 2 Invoking Shell Scripts 2 2.1 Direct Interpretation....................................... 2 2.2 Indirect Interpretation......................................
UNIX, Shell Scripting and Perl Introduction
UNIX, Shell Scripting and Perl Introduction Bart Zeydel 2003 Some useful commands grep searches files for a string. Useful for looking for errors in CAD tool output files. Usage: grep error * (looks for
Perl/CGI. CS 299 Web Programming and Design
Perl/CGI CGI Common: Gateway: Programming in Perl Interface: interacts with many different OSs CGI: server programsprovides uses a well-defined users with a method way to to gain interact access with to
Top 72 Perl Interview Questions and Answers
Top 72 Perl Interview Questions and Answers 1. Difference between the variables in which chomp function work? Scalar: It is denoted by $ symbol. Variable can be a number or a string. Array: Denoted by
?<BACBC;@@A=2(?@?;@=2:;:%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
NGS data format NGS data format @SRR031028.1708655 GGATGATGGATGGATAGATAGATGAAGAGATGGATGGATGGGTGGGTGGTATGCAGCATACCTGAAGTGC BBBCB=ABBB@BA=?BABBBBA??B@BAAA>ABB;@5=@@@?8@:==99:465727:;41'.9>;933!4 @SRR031028.843803
Exercise 1: Python Language Basics
Exercise 1: Python Language Basics In this exercise we will cover the basic principles of the Python language. All languages have a standard set of functionality including the ability to comment code,
CS2043 - Unix Tools & Scripting Lecture 9 Shell Scripting
CS2043 - Unix Tools & Scripting Lecture 9 Shell Scripting Spring 2015 1 February 9, 2015 1 based on slides by Hussam Abu-Libdeh, Bruno Abrahao and David Slater over the years Announcements Coursework adjustments
Advanced Bash Scripting. Joshua Malone ([email protected])
Advanced Bash Scripting Joshua Malone ([email protected]) Why script in bash? You re probably already using it Great at managing external programs Powerful scripting language Portable and version-stable
Lecture 18 Regular Expressions
Lecture 18 Regular Expressions Many of today s web applications require matching patterns in a text document to look for specific information. A good example is parsing a html file to extract tags
grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print
grep, awk and sed three VERY useful command-line utilities Matt Probert, Uni of York grep = global regular expression print In the simplest terms, grep (global regular expression print) will search input
HP-UX Essentials and Shell Programming Course Summary
Contact Us: (616) 875-4060 HP-UX Essentials and Shell Programming Course Summary Length: 5 Days Prerequisite: Basic computer skills Recommendation Statement: Student should be able to use a computer monitor,
Introduction to Shell Programming
Introduction to Shell Programming what is shell programming? about cygwin review of basic UNIX TM pipelines of commands about shell scripts some new commands variables parameters and shift command substitution
#!/usr/bin/perl use strict; use warnings; use Carp; use Data::Dumper; use Tie::IxHash; use Gschem 3; 3. Setup and initialize the global variables.
1. Introduction. This program creates a Bill of Materials (BOM) by parsing a gschem schematic file and grouping components that have identical attributes (except for reference designator). Only components
Informatica e Sistemi in Tempo Reale
Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)
Programming in Perl CSCI-2962 Final Exam
Rules and Information: Programming in Perl CSCI-2962 Final Exam 1. TURN OFF ALL CELULAR PHONES AND PAGERS! 2. Make sure you are seated at least one empty seat away from any other student. 3. Write your
7 Why Use Perl for CGI?
7 Why Use Perl for CGI? Perl is the de facto standard for CGI programming for a number of reasons, but perhaps the most important are: Socket Support: Perl makes it easy to create programs that interface
Thirty Useful Unix Commands
Leaflet U5 Thirty Useful Unix Commands Last revised April 1997 This leaflet contains basic information on thirty of the most frequently used Unix Commands. It is intended for Unix beginners who need a
Hands-On UNIX Exercise:
Hands-On UNIX Exercise: This exercise takes you around some of the features of the shell. Even if you don't need to use them all straight away, it's very useful to be aware of them and to know how to deal
6.170 Tutorial 3 - Ruby Basics
6.170 Tutorial 3 - Ruby Basics Prerequisites 1. Have Ruby installed on your computer a. If you use Mac/Linux, Ruby should already be preinstalled on your machine. b. If you have a Windows Machine, you
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!!)
Apply PERL to BioInformatics (II)
Apply PERL to BioInformatics (II) Lecture Note for Computational Biology 1 (LSM 5191) Jiren Wang http://www.bii.a-star.edu.sg/~jiren BioInformatics Institute Singapore Outline Some examples for manipulating
A Crash Course on UNIX
A Crash Course on UNIX UNIX is an "operating system". Interface between user and data stored on computer. A Windows-style interface is not required. Many flavors of UNIX (and windows interfaces). Solaris,
AN INTRODUCTION TO UNIX
AN INTRODUCTION TO UNIX Paul Johnson School of Mathematics September 24, 2010 OUTLINE 1 SHELL SCRIPTS Shells 2 COMMAND LINE Command Line Input/Output 3 JOBS Processes Job Control 4 NETWORKING Working From
An Introduction to the Linux Command Shell For Beginners
An Introduction to the Linux Command Shell For Beginners Presented by: Victor Gedris In Co-Operation With: The Ottawa Canada Linux Users Group and ExitCertified Copyright and Redistribution This manual
ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters
The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters
Lecture 4: Writing shell scripts
Handout 5 06/03/03 1 Your rst shell script Lecture 4: Writing shell scripts Shell scripts are nothing other than les that contain shell commands that are run when you type the le at the command line. That
Python Lists and Loops
WEEK THREE Python Lists and Loops You ve made it to Week 3, well done! Most programs need to keep track of a list (or collection) of things (e.g. names) at one time or another, and this week we ll show
Lecture 4. Regular Expressions grep and sed intro
Lecture 4 Regular Expressions grep and sed intro Previously Basic UNIX Commands Files: rm, cp, mv, ls, ln Processes: ps, kill Unix Filters cat, head, tail, tee, wc cut, paste find sort, uniq comm, diff,
Linux Syslog Messages in IBM Director
Ever want those pesky little Linux syslog messages (/var/log/messages) to forward to IBM Director? Well, it s not built in, but it s pretty easy to setup. You can forward syslog messages from an IBM Director
Forms, CGI Objectives. HTML forms. Form example. Form example...
The basics of HTML forms How form content is submitted GET, POST Elements that you can have in forms Responding to forms Common Gateway Interface (CGI) Later: Servlets Generation of dynamic Web content
JavaScript: Introduction to Scripting. 2008 Pearson Education, Inc. All rights reserved.
1 6 JavaScript: Introduction to Scripting 2 Comment is free, but facts are sacred. C. P. Scott The creditor hath a better memory than the debtor. James Howell When faced with a decision, I always ask,
BASH Scripting. A bash script may consist of nothing but a series of command lines, e.g. The following helloworld.sh script simply does an echo.
BASH Scripting bash is great for simple scripts that automate things you would otherwise by typing on the command line. Your command line skills will carry over to bash scripting and vice versa. bash comments
A Simple Shopping Cart using CGI
A Simple Shopping Cart using CGI Professor Don Colton, BYU Hawaii March 5, 2004 In this section of the course, we learn to use CGI and Perl to create a simple web-based shopping cart program. We assume
Unix Scripts and Job Scheduling
Unix Scripts and Job Scheduling Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh [email protected] http://www.sis.pitt.edu/~spring Overview Shell Scripts
Lecture 5. sed and awk
Lecture 5 sed and awk Last week Regular Expressions grep egrep Today Stream manipulation: sed awk Sed: Stream-oriented, Non- Interactive, Text Editor Look for patterns one line at a time, like grep Change
1. Stem. Configuration and Use of Stem
Configuration and Use of Stem 1. Stem 2. Why use Stem? 3. What is Stem? 4. Stem Architecture 5. Stem Hubs 6. Stem Messages 7. Stem Addresses 8. Message Types and Fields 9. Message Delivery 10. Stem::Portal
JavaScript: Arrays. 2008 Pearson Education, Inc. All rights reserved.
1 10 JavaScript: Arrays 2 With sobs and tears he sorted out Those of the largest size... Lewis Carroll Attempt the end, and never stand to doubt; Nothing s so hard, but search will find it out. Robert
Perl for System Administration. Jacinta Richardson Paul Fenwick
Perl for System Administration Jacinta Richardson Paul Fenwick Perl for System Administration by Jacinta Richardson and Paul Fenwick Copyright 2006-2008 Jacinta Richardson ([email protected])
Tutorial 0A Programming on the command line
Tutorial 0A Programming on the command line Operating systems User Software Program 1 Program 2 Program n Operating System Hardware CPU Memory Disk Screen Keyboard Mouse 2 Operating systems Microsoft Apple
Programming Languages CIS 443
Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception
Systems Programming & Scripting
Systems Programming & Scripting Lecture 14 - Shell Scripting: Control Structures, Functions Syst Prog & Scripting - Heriot Watt University 1 Control Structures Shell scripting supports creating more complex
Who s Doing What? Analyzing Ethernet LAN Traffic
by Paul Barry, [email protected] Abstract A small collection of Perl modules provides the basic building blocks for the creation of a Perl-based Ethernet network analyzer. I present a network analyzer
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
Regular Expressions and Pattern Matching [email protected]
Regular Expressions and Pattern Matching [email protected] Regular Expression (regex): a separate language, allowing the construction of patterns. used in most programming languages. very powerful
$ftp = Net::FTP->new("some.host.name", Debug => 0) or die "Cannot connect to some.host.name: $@";
NAME Net::FTP - FTP Client class SYNOPSIS use Net::FTP; $ftp = Net::FTP->new("some.host.name", Debug => 0) or die "Cannot connect to some.host.name: $@"; $ftp->login("anonymous",'-anonymous@') or die "Cannot
Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script
Shell Programming Shell Scripts (1) Basically, a shell script is a text file with Unix commands in it. Shell scripts usually begin with a #! and a shell name For example: #!/bin/sh If they do not, the
PYTHON Basics http://hetland.org/writing/instant-hacking.html
CWCS Workshop May 2009 PYTHON Basics http://hetland.org/writing/instant-hacking.html Python is an easy to learn, modern, interpreted, object-oriented programming language. It was designed to be as simple
Basic C Shell. [email protected]. 11th August 2003
Basic C Shell [email protected] 11th August 2003 This is a very brief guide to how to use cshell to speed up your use of Unix commands. Googling C Shell Tutorial can lead you to more detailed information.
Computational Mathematics with Python
Computational Mathematics with Python Basics Claus Führer, Jan Erik Solem, Olivier Verdier Spring 2010 Claus Führer, Jan Erik Solem, Olivier Verdier Computational Mathematics with Python Spring 2010 1
Computational Mathematics with Python
Boolean Arrays Classes Computational Mathematics with Python Basics Olivier Verdier and Claus Führer 2009-03-24 Olivier Verdier and Claus Führer Computational Mathematics with Python 2009-03-24 1 / 40
ESPResSo Summer School 2012
ESPResSo Summer School 2012 Introduction to Tcl Pedro A. Sánchez Institute for Computational Physics Allmandring 3 D-70569 Stuttgart Germany http://www.icp.uni-stuttgart.de 2/26 Outline History, Characteristics,
Bash shell programming Part II Control statements
Bash shell programming Part II Control statements Deniz Savas and Michael Griffiths 2005-2011 Corporate Information and Computing Services The University of Sheffield Email [email protected]
Learning Perl the Hard Way
Learning Perl the Hard Way ii Learning Perl the Hard Way Allen B. Downey Version 0.9 April 16, 2003 Copyright c 2003 Allen Downey. Permission is granted to copy, distribute, and/or modify this document
Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C
Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in
We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.
LING115 Lecture Note Session #4 Python (1) 1. Introduction As we have seen in previous sessions, we can use Linux shell commands to do simple text processing. We now know, for example, how to count words.
Windows PowerShell Essentials
Windows PowerShell Essentials Windows PowerShell Essentials Edition 1.0. This ebook is provided for personal use only. Unauthorized use, reproduction and/or distribution strictly prohibited. All rights
Building Software Systems. Multi-module C Programs. Example Multi-module C Program. Example Multi-module C Program
Building Software Systems Multi-module C Programs Software systems need to be built / re-built during the development phase if distributed in source code form (change,compile,test,repeat) (assists portability)
Linux command line. An introduction to the Linux command line for genomics. Susan Fairley
Linux command line An introduction to the Linux command line for genomics Susan Fairley Aims Introduce the command line Provide an awareness of basic functionality Illustrate with some examples Provide
Eventia Log Parsing Editor 1.0 Administration Guide
Eventia Log Parsing Editor 1.0 Administration Guide Revised: November 28, 2007 In This Document Overview page 2 Installation and Supported Platforms page 4 Menus and Main Window page 5 Creating Parsing
Command Scripts. 13.1 Running scripts: include and commands
13 Command Scripts You will probably find that your most intensive use of AMPL s command environment occurs during the initial development of a model, when the results are unfamiliar and changes are frequent.
Basics of I/O Streams and File I/O
Basics of This is like a cheat sheet for file I/O in C++. It summarizes the steps you must take to do basic I/O to and from files, with only a tiny bit of explanation. It is not a replacement for reading
10.1 The Common Gateway Interface
10.1 The Common Gateway Interface - Markup languages cannot be used to specify computations, interactions with users, or to provide access to databases - CGI is a common way to provide for these needs,
CGI.pm Tutorial. Table of content. What is CGI? First Program
CGI.pm Tutorial This is a tutorial on CGI.pm which include scripts to let you see the effects. CGI.pm is a Perl module to facilitate the writing of CGI scripts. Click here to see the details. This tutorial
Software documentation systems
Software documentation systems Basic introduction to various user-oriented and developer-oriented software documentation systems. Ondrej Holotnak Ondrej Jombik Software documentation systems: Basic introduction
An Introduction to Assembly Programming with the ARM 32-bit Processor Family
An Introduction to Assembly Programming with the ARM 32-bit Processor Family G. Agosta Politecnico di Milano December 3, 2011 Contents 1 Introduction 1 1.1 Prerequisites............................. 2
Regular Expressions Overview Suppose you needed to find a specific IPv4 address in a bunch of files? This is easy to do; you just specify the IP
Regular Expressions Overview Suppose you needed to find a specific IPv4 address in a bunch of files? This is easy to do; you just specify the IP address as a string and do a search. But, what if you didn
How to Write a Simple Makefile
Chapter 1 CHAPTER 1 How to Write a Simple Makefile The mechanics of programming usually follow a fairly simple routine of editing source files, compiling the source into an executable form, and debugging
JavaScript: Control Statements I
1 7 JavaScript: Control Statements I 7.1 Introduction 2 The techniques you will learn here are applicable to most high-level languages, including JavaScript 1 7.2 Algorithms 3 Any computable problem can
LECTURE-7. Introduction to DOS. Introduction to UNIX/LINUX OS. Introduction to Windows. Topics:
Topics: LECTURE-7 Introduction to DOS. Introduction to UNIX/LINUX OS. Introduction to Windows. BASIC INTRODUCTION TO DOS OPERATING SYSTEM DISK OPERATING SYSTEM (DOS) In the 1980s or early 1990s, the operating
Member Functions of the istream Class
Member Functions of the istream Class The extraction operator is of limited use because it always uses whitespace to delimit its reads of the input stream. It cannot be used to read those whitespace characters,
Finding XSS in Real World
Finding XSS in Real World by Alexander Korznikov [email protected] 1 April 2015 Hi there, in this tutorial, I will try to explain how to find XSS in real world, using some interesting techniques. All
AWK: The Duct Tape of Computer Science Research. Tim Sherwood UC Santa Barbara
AWK: The Duct Tape of Computer Science Research Tim Sherwood UC Santa Barbara Duct Tape Systems Research Environment Lots of simulators, data, and analysis tools Since it is research, nothing works together
Regular Expressions. In This Appendix
A Expressions In This Appendix Characters................... 888 Delimiters................... 888 Simple Strings................ 888 Special Characters............ 888 Rules....................... 891
CS106A, Stanford Handout #38. Strings and Chars
CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars The char type (pronounced "car") represents a single character. A char literal value can be written in the code using single quotes
Introduction to Shell Scripting
Introduction to Shell Scripting Lecture 1. Shell scripts are small programs. They let you automate multi-step processes, and give you the capability to use decision-making logic and repetitive loops. 2.
The C Programming Language course syllabus associate level
TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming
Command Line Crash Course For Unix
Command Line Crash Course For Unix Controlling Your Computer From The Terminal Zed A. Shaw December 2011 Introduction How To Use This Course You cannot learn to do this from videos alone. You can learn
Beginners Shell Scripting for Batch Jobs
Beginners Shell Scripting for Batch Jobs Evan Bollig and Geoffrey Womeldorff Before we begin... Everyone please visit this page for example scripts and grab a crib sheet from the front http://www.scs.fsu.edu/~bollig/techseries
List of FTP commands for the Microsoft command-line FTP client
You are on the nsftools.com site This is a list of the commands available when using the Microsoft Windows command-line FTP client (requires TCP/IP to be installed). All information is from the Windows
ICS 351: Today's plan
ICS 351: Today's plan routing protocols linux commands Routing protocols: overview maintaining the routing tables is very labor-intensive if done manually so routing tables are maintained automatically:
Computational Mathematics with Python
Numerical Analysis, Lund University, 2011 1 Computational Mathematics with Python Chapter 1: Basics Numerical Analysis, Lund University Claus Führer, Jan Erik Solem, Olivier Verdier, Tony Stillfjord Spring
Pseudo code Tutorial and Exercises Teacher s Version
Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy
Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)
Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the
Example of a Java program
Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);
PL / SQL Basics. Chapter 3
PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic
