Practical Extraction and Report Language. «Perl is a language of getting your job done» «There is more than one way to do it»

Size: px
Start display at page:

Download "Practical Extraction and Report Language. «Perl is a language of getting your job done» «There is more than one way to do it»"

Transcription

1 Practical Extraction and Report Language «Perl is a language of getting your job done» «There is more than one way to do it» IOANNIDIS Vassilios Swiss Institute of Bioinformatics EMBnet Group Quartier Sorge - Batiment Genopode CH-1015 Lausanne - Switzerland T: vassilios.ioannidis@isb-sib.ch Larry Wall VI, September 2008 Page 1 Perl Outline : Filehandles & File Tests Subroutines (functions) References passing arguments to functions nested data structure Packages/Modules Namespace/@INC VI, September 2008 Page 2

2 Perl Files vioannid$ less list_dos.txt Mrs. Bausch Damaris^MMr. Burckhardt Christoph^MDr. (Mrs.) Casado Begona^MMr. Dalla Torre Simon^MMr. Hammann Felix^MDr. (Mr.) Heller Manfred^MMr. Hurschler Benjamin^MMr. Klemm Sebastian^MMrs. List Claudia^MMr. Ludin Philipp^MMr. Mannhart Lukas^MMrs. Mathimaran Vinodha^MDr. (Mr.) Muller Andreas^MMrs. Oberhansli Simone^MMrs. Roltgen Katharina^MDr. (Mrs.) Schweizer Magali^MMrs. Suenderhauf Claudia^MDr. (Mr.) Tzouros Manuel^MMrs. Uplekar Swapna^MDr. (Mrs.) Vuillet Laurie^MMr. Watkins Stephan Lloyd^MMr. Young Thomas vioannid$ od -c list_dos.txt M r s. \t B a u s c h \t D a m a r i s \r M r. \t B u r c k h a r d t \t C h r i s t o p h \r D r ( M r s. ) \t C a s a d o \t B e g o n a \r M r. \t D a l l a T o r r e \t S i m o n \r M r. \t H a m m a n n \t F e l i x \r D r ( M r. ) \t H e l l e r \t M a n f r e d \r M r. \t H u r s c h l e r \t B e n j a m i n \r M r \t K l e m m \t S e b a s t i a n \r M r s. \t L i s t \t C l a u d i a \r M r. \t L u d i n \t P h i l i p p \r M r. \t M a n n h a r t \t L u k a s \r M r s. \t M a t h i m a r a n \t V i n o d h a \r D r. ( M r. ) \t M u l l e r \t A n d r e a s \r M r s. \t O Important: Unix & all Unix flavors: Mac OS : Windows: \n \r \r\n Unix command: tr vioannid$ tr '\r' '\n' < list_dos.txt > list.txt Perl command: s/// vioannid$ perl -p -e 's/\r/\n/g' < list_dos.txt > list.txt VI, September 2008 Page 3 Perl Files vioannid$ less list.txt Mrs. Bausch Damaris Mr. Burckhardt Christoph Dr. (Mrs.) Casado Begona Mr. Dalla Torre Simon Mr. Hammann Felix Dr. (Mr.) Heller Manfred Mr. Hurschler Benjamin Mr. Klemm Sebastian Mrs. List Claudia Mr. Ludin Philipp Mr. Mannhart Lukas Mrs. Mathimaran Vinodha Dr. (Mr.) Muller Andreas Mrs. Oberhansli Simone Mrs. Roltgen Katharina Dr. (Mrs.) Schweizer Magali Mrs. Suenderhauf Claudia Dr. (Mr.) Tzouros Manuel Mrs. Uplekar Swapna Dr. (Mrs.) Vuillet Laurie Mr. Watkins Stephan Lloyd Mr. Young Thomas VI, September 2008 vioannid$ od -c list_dos.txt M r s. \t B a u s c h \t D a m a r i s \n M r. \t B u r c k h a r d t \t C h r i s t o p h \n D r ( M r s. ) \t C a s a d o \t B e g o n a \n M r. \t D a l l a T o r r e \t S i m o n \n M r. \t H a m m a n n \t F e l i x \n D r ( M r. ) \t H e l l e r \t M a n f r e d \n M r. \t H u r s c h l e r \t B e n j a m i n \n M r \t K l e m m \t S e b a s t i a n \n M r s. \t L i s t \t C l a u d i a \n M r. \t L u d i n \t P h i l i p p \n M r. \t M a n n h a r t \t L u k a s \n M r s. \t M a t h i m a r a n \t V i n o d h a \n D r. ( M r. ) \t M u l l e r \t A n d r e a s \n M r s. \t O b e r h a n s l i \t S i m o n e Page 4

3 Perl Filehandles A filehandle is the name in a Perl program for an I/O connection between your Perl process and the outside world. (Good practice: use all uppercase letters in the name of your filehandle) Perl special file handles There are three connections that always exist and are always "open" when your program starts: STDIN, STDOUT, and STDERR. Actually, these names are file handles. File handles are variables used to manipulate files. STDIN reads from standard input which is usually the keyboard in normal Perl script (or input from a Browser in a CGI script. Cgi-lib.pl reads from this automatically.) STDOUT (standard output) and STDERR (standard error) by default write to a console (or a browser in CGI). We have been using the STDOUT file handle without knowing it for every print() statement during Perl presentations. The print() function uses STDOUT as the default if no other file handle is specified. VI, September 2008 Page 5 Perl - Getting User Input How to get a value from the keyboard into a Perl program? The simplest way is to use the line-input operator: <STDIN> Each time we use <STDIN> in a place where a scalar value is expected, Perl reads the next complete text line up to the first newline from the keyboard (unless you modified it). print "Please enter your Lastname: "; my $lastname = <STDIN>; chomp $lastname; Please enter your Lastname: Ioannidis print "Please enter your Firstname: "; my $firstname = <STDIN>; chomp $firstname; Please enter your Firstname: Hello Vassilios Ioannidis, I hope you like Perl programming! Vassilios print "Hello $firstname $lastname,\n I hope you like Perl programming!\n"; exit; VI, September 2008 Page 6

4 Perl Filehandles vioannid$ cat course_list.csv List;Claudia;Mrs.;Basel;4051; Hammann;Felix;Mr.;Basel;4031; Vuillet;Laurie;Dr. (Mrs.) ;Lausanne;1015; Suenderhauf;Claudia;Mrs.;Basel;4058; Roltgen;Katharina;Mrs.;Basel;4051; Klemm;Sebastian;Mr.;Basel;4056; Young;Thomas;Mr.;Zurich;8032; Muller;Andreas;Dr. (Mr.);Basel;4002; Schweizer;Magali;Dr. (Mrs.) ;Zurich;8092; Watkins;Stephan Lloyd;Mr.;Bern;3012; Tzouros;Manuel;Dr. (Mr.);Basel;4070; Uplekar;Swapna;Mrs.;Lausanne;1015; Burckhardt;Christoph;Mr.;Zurich;8057; Mathimaran;Vinodha;Mrs.;Basel;4056; Oberhansli;Simone;Mrs.;Zurich;8008; Ludin;Philipp;Mr.;Bern;3012; Bausch;Damaris;Mrs.;Zurich;8093; Dalla Torre;Simon;Mr.;Basel;4056; Casado;Begona;Dr. (Mrs.) ;Lausanne;1000; Mannhart;Lukas;Mr.;Basel;4058; Hurschler;Benjamin;Mr.;Basel;4058; vioannid VI, September 2008 Page 7 The invocation Perl Filehandles open (FILE, "course_list.csv") or die "Error. Could not open the file!\n"; while (<FILE>) { if (m/^(.*);(.*);(.*);(.*);(.*);$/) { print "Hello $3 $2 $1 from $4!\n"; else { exit; vioannid$./course_list.pl Hello Mrs. Claudia List from Basel! Hello Mr. Felix Hammann from Basel! Hello Dr. (Mrs.) Laurie Vuillet from Lausanne! Hello Mrs. Claudia Suenderhauf from Basel! Hello Mrs. Katharina Roltgen from Basel! Hello Mr. Sebastian Klemm from Basel! Hello Mr. Thomas Young from Zurich! Hello Dr. (Mr.) Andreas Muller from Basel! Hello Dr. (Mrs.) Magali Schweizer from Zurich! Hello Mr. Stephan Lloyd Watkins from Bern! Hello Dr. (Mr.) Manuel Tzouros from Basel! Hello Mrs. Swapna Uplekar from Lausanne! Hello Mr. Christoph Burckhardt from Zurich! Hello Mrs. Vinodha Mathimaran from Basel! Hello Mrs. Simone Oberhansli from Zurich! Hello Mr. Philipp Ludin from Bern! Hello Mrs. Damaris Bausch from Zurich! Hello Mr. Simon Dalla Torre from Basel! Hello Dr. (Mrs.) Begona Casado from Lausanne! Hello Mr. Lukas Mannhart from Basel! Hello Mr. Benjamin Hurschler from Basel! VI, September 2008 Page 8

5 Perl Filehandles The invocation Technically, the diamond <> operator is not looking literally at the invocation argument. It works from array. This is a special array that is preset by Perl to be a list of the invocation arguments. When the program contains the list of invocation arguments. And can be handled as a just like any other array! vioannid$./argv1.pl course_list.csv course_list.csv my $nb_arg my $argument = $ARGV[0]; print "\n$nb_arg\n"; print "The invocation argument is: $argument\n"; 1 The invocation argument is: course_list.csv exit; VI, September 2008 Page 9 The invocation Perl Filehandles my $filename = $ARGV[0]; open (FILE, "$filename") or die "Error. Could not open the file $filename!\n"; while (<FILE>) { if (m/^(.*);(.*);(.*);(.*);(.*);$/) { print "Hello $3 $2 $1 from $4!\n"; else { exit; vioannid$./argv2.pl course_list.csv Hello Mrs. Claudia List from Basel! Hello Mr. Felix Hammann from Basel! Hello Dr. (Mrs.) Laurie Vuillet from Lausanne! Hello Mrs. Claudia Suenderhauf from Basel! Hello Mrs. Katharina Roltgen from Basel! Hello Mr. Sebastian Klemm from Basel! Hello Mr. Thomas Young from Zurich! Hello Dr. (Mr.) Andreas Muller from Basel! Hello Dr. (Mrs.) Magali Schweizer from Zurich! Hello Mr. Stephan Lloyd Watkins from Bern! Hello Dr. (Mr.) Manuel Tzouros from Basel! Hello Mrs. Swapna Uplekar from Lausanne! Hello Mr. Christoph Burckhardt from Zurich! Hello Mrs. Vinodha Mathimaran from Basel! Hello Mrs. Simone Oberhansli from Zurich! Hello Mr. Philipp Ludin from Bern! Hello Mrs. Damaris Bausch from Zurich! Hello Mr. Simon Dalla Torre from Basel! Hello Dr. (Mrs.) Begona Casado from Lausanne! Hello Mr. Lukas Mannhart from Basel! Hello Mr. Benjamin Hurschler from Basel! VI, September 2008 Page 10

6 Perl Filehandles You can open a file for input or output using the open() function. open(infile, "input.txt") or die "Can't open input.txt: $!"; open(outfile, ">output.txt") or die "Can't open output.txt: $!"; open(logfile, ">>logfile") or die "Can't open logfile: $!"; You can use your own naming instead of "INFILE", "OUTFILE" or "LOGFILE". When you're done with your filehandles, you should close() them (though Perl will clean up after you if you forget ): close INFILE; print() can also take an optional first argument specifying which filehandle to print to: print STDERR "This is your final warning\n"; print OUTFILE $record; print LOGFILE $logmessage; use whatever name you like BUT: STDIN, STDOUT, STDERR, ARGV! VI, September 2008 Page 11 Perl Filehandles File test Meaning -r File is readable by effective user/group. -w File is writable by effective user/group. -x File is executable by effective user/group. -o File is owned by effective user. -R File is readable by real user/group. -W File is writable by real user/group. -X File is executable by real user/group. -O File is owned by real user. -e File exists. -z File has zero size. -s File has nonzero size (returns size). -f File is a plain file. -d File is a directory. -l File is a symbolic link. File test Meaning -p File is a named pipe (FIFO). -S File is a socket. -b File is a block special file. -c File is a character special file. -t Filehandle is opened to a tty. -u File has setuser bit set. -g File has setgroup bit set. -k File has sticky bit set. -T File is a text file. -B File is a binary file (opposite of -T). -M Age of file (at startup) in days since modification. -A Age of file (at startup) in days since last access. -C Age of file (at startup) in days since inode change. VI, September 2008 Page if (-e $filename) { #do something...

7 Perl Filehandles You can read from an open filehandle using the "<>" operator. In scalar context it reads a single line (or a single record) from the filehandle, and in list context it reads the whole file in, assigning each line to an element of the list: my $line = <INFILE>; = <INFILE>; Reading in the whole file at one time is called slurping. It can be useful but it may be a memory hog. Most text file processing can be done a line at a time with Perl's looping constructs. The "<>" operator is most often seen in a while loop: while (<INFILE>) { # assigns each line in turn to $_ print "Just read in this line: $_"; close INFILE; VI, September 2008 Page 13 Perl Filehandles You can read from an open filehandle using the "<>" operator. In scalar context it reads a single line (or a single record) from the filehandle. Most text file processing can be done a line at a time with Perl's looping constructs. The "<>" operator is most often seen in a while loop: >3BHS1_RAT PGWSCLVTGAGGFVGQRIIRMLVQEKELQEVRALDKVFRPETKEEFSKLQTKAKVTMLEG DILDAQYLRRACQGISVVIHTAAVIDVSHVLPRQTILDVNLKGTQNILEACVEASVPAFI YCSTVDVAGPNSYKKIILNGHEEEHHESTWSDAYPYSKRMAEKAVLAANGSILKNGGTLH TCALRPMYIYGERSPFLSVMILAALKNKGILNVTGKFSIANPVYVGNVAWAHILAARGLR DPKKSQNVQGQFYYISDDTPHQSYDDLNCTLSKEWGLRLDSSWSLPLPLLYWLAFLLETV SFLLRPFYNYRPPFNCHLVTLSNSKFTFSYKKAQRDLGYVPLVSWEEAKQKTSEWIGTLV EQHRETLDTKSQ >3BHS2_RAT PGWSCLVTGAGGFVGQRIIRMLVQEKELQEVRALDKVFRPETKEEFSKLQTKAKVTMLEG DILDAQYLRRACQGISVVIHTASVMDFSRVLPRQTILDVNLKGTQNLLEAGIHASVPAFI YCSTVDVAGPNSYKKTILNGREEEHHESTWSNPYPYSKKMAEKAVLAANGSILKNGGTLH TCALRPMYIYGERGQFLSRIIIMALKNKGVLNVTGKFSIVNPVYVGNVAWAHILAARGLR DPKKSQNIQGQFYYISDDTPHQSYDDLNCTLSKEWGLRLDSSWSLPLPLLYWLAFLLETV SFLLRPFYNYRPPFNCHLVTLSNSKFTFSYKKAQRDLGYEPLVSWEEAKQKTSEWIGTLV EQHRETLDTKSQ >3BHS4_RAT PGWSCLVTGAGGFLGQRIVQLLVQEKDLKEVRVLDKVFRPETREEFFNLGTSIKVTVLEG DILDTQCLRRACQGISVVIHTAALIDVTGVNPRQTILDVNLKGTQNLLEACVQASVPAFI... VI, September 2008 Page 14

8 Perl Filehandles You can read from an open filehandle using the "<>" operator. In scalar context it reads a single line (or a single record) from the filehandle. Most text file processing can be done a line at a time with Perl's looping constructs. The "<>" operator is most often seen in a while loop: ID 3BHS1_RAT STANDARD; PRT; 372 AA. AC P22071;..... SQ SEQUENCE 372 AA; MW; F989617C1AF18949 CRC64; PGWSCLVTGA GGFVGQRIIR MLVQEKELQE VRALDKVFRP ETKEEFSKLQ TKAKVTMLEG DILDAQYLRR ACQGISVVIH TAAVIDVSHV LPRQTILDVN LKGTQNILEA CVEASVPAFI YCSTVDVAGP NSYKKIILNG HEEEHHESTW SDAYPYSKRM AEKAVLAANG SILKNGGTLH TCALRPMYIY GERSPFLSVM ILAALKNKGI LNVTGKFSIA NPVYVGNVAW AHILAARGLR DPKKSQNVQG QFYYISDDTP HQSYDDLNCT LSKEWGLRLD SSWSLPLPLL YWLAFLLETV SFLLRPFYNY RPPFNCHLVT LSNSKFTFSY KKAQRDLGYV PLVSWEEAKQ KTSEWIGTLV EQHRETLDTK SQ // ID 3BHS2_RAT STANDARD; PRT; 372 AA. AC P22072;..... SQ SEQUENCE 372 AA; MW; EDAB175F3F33334B CRC64; PGWSCLVTGA GGFVGQRIIR MLVQEKELQE VRALDKVFRP ETKEEFSKLQ TKAKVTMLEG DILDAQYLRR ACQGISVVIH TASVMDFSRV LPRQTILDVN LKGTQNLLEA GIHASVPAFI YCSTVDVAGP NSYKKTILNG REEEHHESTW SNPYPYSKKM AEKAVLAANG SILKNGGTLH TCALRPMYIY GERGQFLSRI IIMALKNKGV LNVTGKFSIV NPVYVGNVAW AHILAARGLR DPKKSQNIQG QFYYISDDTP HQSYDDLNCT LSKEWGLRLD SSWSLPLPLL YWLAFLLETV SFLLRPFYNY RPPFNCHLVT LSNSKFTFSY KKAQRDLGYE PLVSWEEAKQ KTSEWIGTLV EQHRETLDTK SQ // VI, September 2008 Page 15 Perl Filehandles You can modify the regular record separator "\n" by something else: $/= "\n//\n"; for a file containing SwissProt entries or $/=">"; for a fasta file $/=">"; while (<INFILE>) { # assigns each line in turn to $_ print "Entry: $_"; vioannid$./any_script.pl Entry:>Entry:3BHS1_RAT PGWSCLVTGAGGFVGQRIIRMLVQEKELQEVRALDKVFRPETKEEFSKLQTKAKVTMLEG DILDAQYLRRACQGISVVIHTAAVIDVSHVLPRQTILDVNLKGTQNILEACVEASVPAFI YCSTVDVAGPNSYKKIILNGHEEEHHESTWSDAYPYSKRMAEKAVLAANGSILKNGGTLH TCALRPMYIYGERSPFLSVMILAALKNKGILNVTGKFSIANPVYVGNVAWAHILAARGLR DPKKSQNVQGQFYYISDDTPHQSYDDLNCTLSKEWGLRLDSSWSLPLPLLYWLAFLLETV SFLLRPFYNYRPPFNCHLVTLSNSKFTFSYKKAQRDLGYVPLVSWEEAKQKTSEWIGTLV EQHRETLDTKSQ >Entry:3BHS2_RAT PGWSCLVTGAGGFVGQRIIRMLVQEKELQEVRALDKVFRPETKEEFSKLQTKAKVTMLEG DILDAQYLRRACQGISVVIHTASVMDFSRVLPRQTILDVNLKGTQNLLEAGIHASVPAFI YCSTVDVAGPNSYKKTILNGREEEHHESTWSNPYPYSKKMAEKAVLAANGSILKNGGTLH TCALRPMYIYGERGQFLSRIIIMALKNKGVLNVTGKFSIVNPVYVGNVAWAHILAARGLR DPKKSQNIQGQFYYISDDTPHQSYDDLNCTLSKEWGLRLDSSWSLPLPLLYWLAFLLETV SFLLRPFYNYRPPFNCHLVTLSNSKFTFSYKKAQRDLGYEPLVSWEEAKQKTSEWIGTLV EQHRETLDTKSQ..... VI, September 2008 Page 16

9 Perl Outline : Filehandles & File Tests Subroutines (functions) References passing arguments to functions nested data structure Packages/Modules Namespace/@INC VI, September 2008 Page 17 Perl Subroutines = ("Claudia", "Felix", "Laurie", "Thomas","Simone"); foreach (@names1 ) { my $size = length($_); print '*'x($size+2),"\n"; print "*$_*\n"; print '*'x($size+2),"\n"; exit ; vioannid$./sub1.pl * *Claudia* * ******* *Felix* ******* *Laurie* *Thomas* *Simone* VI, September 2008 Page 18

10 Perl Subroutines = ("Claudia", "Felix", "Laurie", "Thomas","Simone"); foreach (@names1 ) { my $size = length($_); print '*'x($size+2),"\n"; print "*$_*\n"; print '*'x($size+2),"\n"; = ("Benjamin","Lukas","Begona","Simon"); foreach (@names2 ) { my $size = length($_); print '*'x($size+2),"\n"; print "*$_*\n"; print '*'x($size+2),"\n"; = ("Christoph","Swapna","Manuel","Magali"); foreach (@names3 ) { my $size = length($_); print '*'x($size+2),"\n"; print "*$_*\n"; print '*'x($size+2),"\n"; vioannid$./sub2.pl * *Claudia* * ******* *Felix* ******* *Laurie* *Swapna* *Manuel* *Magali* exit ; VI, September 2008 Page 19 Perl Subroutines Functions in Perl are called subroutines A subroutine is a named, reusable, and accessible chunk of code that was written to accomplish a specific goal. Therefore, functions are useful to avoid typing redundant code over and over. Functions help in the clarity of scripts. Don't reinvent the wheel!!! There are already many available functions in Perl: VI, September 2008 Page 20

11 Perl Subroutines (procedure, function) #defining subroutine sub myfunc { my $param = shift(@_);... return $result; # calling a function $calcul = myfunc($value); #defining subroutine sub myproc { my $param = shift(@_);... return; # calling procedure myproc($value); Some Perl commands tell the Perl interpreter to do something. A statement starting with a "verb" is generally purely imperative. We often call these "verbs" procedures: a frequently seen command is the print command. Some verbs are for asking questions, and are useful in conditional statements. Other verbs translate their input parameters into return values, just as a recipe tells you how to turn raw ingredients into something (hopefully) edible. We tend to call these verbs functions. VI, September 2008 Page 21 Perl Subroutines = ("Claudia", "Felix", "Laurie", "Thomas","Simone"); = ("Benjamin","Lukas","Begona","Simon"); = ("Christoph","Swapna","Manuel","Magali"); &pretty_print(@names1); &pretty_print(@names2); &pretty_print(@names3); exit ; sub pretty_print { foreach (@_) { my $size = length($_); print '*'x($size+2),"\n"; print "*$_*\n"; print '*'x($size+2),"\n"; vioannid$./sub3.pl * *Claudia* * ******* *Felix* ******* *Laurie* *Swapna* *Manuel* *Magali* VI, September 2008 Page 22

12 Perl functions #call the helloworld function #& is optional with parentheses helloworld(); vioannid$./sub_hello.pl hello World! vioannid$ #tell the program to exit exit; sub helloworld{ print "hello World!\n"; In the same manner than $ stands for for arrays and % for hashes, & stands for subroutines (optional when () are used). Note, however, that in practice, helloworld(); is preferred to &helloworld; VI, September 2008 Page 23 Perl functions vioannid$./sub_sum.pl 46 vioannid$ # pass 2 arguments to the plus function # receive the output in $sum my $sum = plus(12,34); print "$sum\n"; exit; sub plus{ my($x, $y)=@_; return $x+$y; In order to accomplish this goal a subroutine can sometimes need input, or what are called input parameters. In this case, the list of those parameters will be caught through the default VI, September 2008 Page 24

13 Perl functions vioannid$./sub_sum_array.pl sum=18 vioannid$ 4, 5, 8); my $sum = &plus(@vals); print "sum=$sum\n"; sub plus{ my $add = 0; foreach(@values){ $add += $_; return $add; VI, September 2008 Page 25 Perl functions Checking/Detecting parameters Checking the number of parameters A common problem is to check the number of parameters (and maybe return an is a normal array, therefore: my $nbparam = Detecting a parameter type with ref($x) (is it a scalar? an array reference? a file handle?) ref($x) will return a string with the type of the argument: empty string for scalar, ARRAY for array, HASH for hash table, GLOB for a file handle etc. Detecting the parameters type allows to handle in the same subroutine many different situations. VI, September 2008 Page 26

14 Perl Scope of Variables Scope refers to the visibility of variables. In other words, which parts of your program can see or use them. = ( "Simon","Magali", "Lukas","Swapna" ); vioannid$./scope.pl Global symbol "$name" requires explicit package name at./scope.pl line 12. Execution of./scope.pl aborted due to compilation errors. vioannid$ foreach my $name (@list) { print "Hello $name!\n"; Lexical Scope print "Hello $name!\n"; Lexical scope is more ideal for the majority of variables programmers use regularly. Lexical scope allows a variable exit ; to exist only within its containing closure. The widest scope available to a lexical variable is the entire file in which its declared. No entry is created in the symbol table for lexically scoped variables and these variables will be purged once they're out of scope. This use of Perl's garbage collection can save resources and prevent variable collisions. Lexical scope has to be declared by using Perl's my() function. Variables have to be declared with "use strict". VI, September 2008 Page 27 Perl Scope of Variables my $a = 5; my $b = 10; print '$a before: '."$a\n"; print '$b before: '."$b\n\n"; vioannid$./scope2.pl $a before: 5 $b before: 10 double, $a: 10 double, $b: 20 $a after: 10 $b after: 20 vioannid$ double($a,$b); print '$a after: '."$a\n"; print '$b after: '."$b\n"; exit ; sub double { $a = shift; #$a = $_[0]; $b = shift; #$b = $_[1]; $a=$a*2; $b=$b*2; print 'double, $a: '."$a\n"; print 'double, $b: '."$b\n\n"; VI, September 2008 Page 28

15 Perl Scope of Variables my $a = 5; my $b = 10; print '$a before: '."$a\n"; print '$b before: '."$b\n\n"; vioannid$./scope3.pl $a before: 5 $b before: 10 double, $a: 10 double, $b: 20 $a after: 5 $b after: 10 vioannid$ double($a,$b); print '$a after: '."$a\n"; print '$b after: '."$b\n"; exit ; sub double { my $a = shift; #my $a = $_[0]; my $b = shift; #my $b = $_[1]; $a=$a*2; $b=$b*2; print 'double, $a: '."$a\n"; print 'double, $b: '."$b\n\n"; VI, September 2008 Page 29 Perl functions = ("Claudia", "Felix", "Laurie"); = ("Thomas","Simone"); print "@list1\n"; print "@list2\n"; list(@list1,@list2); exit ; sub list { ; print("the first array print("the second array vioannid$./scope4.pl Claudia Felix Laurie Thomas Simone The first array is Claudia Felix Laurie Thomas Simone. The second array is. VI, September 2008 Page 30

16 Perl Outline : Filehandles & File Tests Subroutines (functions) References passing arguments to functions nested data structure Packages/Modules Namespace/@INC VI, September 2008 Page 31 Perl References References If you want to pass more than one array or hash into a function (or return them from it) and maintain their integrity, then you have to use an explicit pass-byreference In Perl, you can pass only one kind of argument to a subroutine: a scalar. You do that by passing a reference to it. A reference to anything is a scalar. Think at a reference as the Macintosh's alias or the Windows's shortcut. VI, September 2008 Page 32

17 Perl References References If you want to pass more than one array or hash into a function (or return them from it) and maintain their integrity, then you have to use an explicit pass-byreference In Perl, you can pass only one kind of argument to a subroutine: a scalar. You do that by passing a reference to it. A reference to anything is a scalar. Think at a reference as the Macintosh's alias or the Windows's shortcut. (an array with \@list_names value john magdalena luc john magdalena luc 0x180b324 "address" 0x180b524 0x180b324 0x180b318 VI, September 2008 Page 33 Perl References = ("Laurie", "Felix", "Claudia"); = ("Thomas","Simone"); print "\nbefore the list function:\n"; print "list print "list list(\@list1,\@list2); print "\n\nafter the list function:\n"; print "@list1\n"; print "@list2\n\n"; exit ; vioannid$./scope5.pl Before the list function: list 1: Laurie Felix Claudia list 2: Thomas Simone Within the list function: list 1: Claudia Felix Laurie. list 2: Simone Thomas. After the list function: Claudia Felix Laurie Simone Thomas sub list { my $ref1 = shift; my $ref2 = = print "\n\nwithin the list function:\n"; print "list print "list VI, September 2008 Page 34

18 Perl References References The following table discusses the referencing and de-referencing of variables. Note that in the case of lists and hashes, you reference and dereference the list or hash as a whole, not individual elements. Variable Instantiating the scalar Instantiating a reference to it Referencing it Dereferencing it Accessing an element $scalar $scalar="steve"; ${$ref $ref = \$scalar $$ref = ( "steve", "fred" ); $ref = [ "steve", "fred" ]; $ref ${$ref[1] $ref->[1] %hash %hash = ( "name" => "steve", "job" => "DJ" ); $hash = { "name" => "steve", "job" => "DJ" ; $ref = \%hash %{$ref %$ref ${$ref{"name" $ref->{"job" VI, September 2008 Page 35 Perl References References vioannid$./ref1.pl my %hash = ( "name" => "steve", "job" => "DJ" ); my $ref = \%hash; print ${$ref{"name"; print "\n"; print $ref->{'job'; print "\n"; my %hash_copy = %$ref; print %hash_copy; print "\n"; steve DJ namestevejobdj exit; VI, September 2008 Page 36

19 Perl References References vioannid$./ref2.pl = ( "bruce", "michael" ); my $ref2 = \@list; print ${$ref2[0]; print "\n"; print $ref2->[1]; print "\n"; bruce michael print "\n"; brucemichael exit; VI, September 2008 Page 37 Perl Outline : Filehandles & File Tests Subroutines (functions) References passing arguments to functions nested data structure Packages/Modules Namespace/@INC VI, September 2008 Page 38

20 Perl Nested Data Structures References are commonly used in Nested Data Structures: ARRAY REF ARRAY REF Gene1 ARRAY REF Gene2 ARRAY REF AKT_signaling LCK_signaling Erk BRCA-1_pathway Integrin_signaling TCF-1_pathway VI, September 2008 Page 39 Perl Nested Data Structures References are commonly used in Nested Data Structures: = qw(akt_signaling Erk Integrin_signaling); = ('gene1', \@gene1); =qw(lck_signaling BRCA-1_pathway TCF-1_pathway ); = ('gene2', \@gene2); = (\@gene1_name,\@gene2_name,); ; print "\n"; ; print "\n"; my $value_array_gene_name_refs1 print $value_array_gene_name_refs1 ; print "\n"; my $value_array2_field3 = ${${$all_gene_names[1][1][2]; print $value_array2_field3; print "\n"; ARRAY(0x180b318)ARRAY(0x180d888) gene1array(0x180b324) gene1 TCF-1_pathway exit; VI, September 2008 Page 40

21 Perl Nested Data Structures References are commonly used in Nested Data Structures: Arrays of arrays Hashes of arrays Arrays of Hashes Hashes of hashes And more! When the nested data structures become to complex, it may be worth considering Object Oriented Perl programming VI, September 2008 Page 41 Perl script1.pl my $v1 = complex_operation (param1);... my $v2 = complex_operation (param2); script2.pl my $v1 = complex_operation (param1);... my $v2 = complex_operation (param2); exit ; exit ; sub complex_operation { sub complex_operation { VI, September 2008 Page 42

22 Perl Outline : Filehandles & File Tests Subroutines (functions) References passing arguments to functions nested data structure Packages/Modules Namespace/@INC VI, September 2008 Page 43 Perl Package/Module script1.pl use Mymod; my $v1 = Mymod::complex_operation (param1);... my $v2 = Mymod::complex_operation (param2);... script2.pl use Mymod; Module Mymod sub complex_operation { my $v1 = Mymod::complex_operation (param1);... my $v2 = Mymod::complex_operation (param2);... VI, September 2008 Page 44

23 Perl Package/Module Structure of module Mymod.pm Calling the functions in a script package Mymod; sub f { sub g = ( ); 1; use Mymod; Mymod::f($param); $a = Mymod::g(); A module is a package defined in a file whose name is the same as the package. VI, September 2008 Page 45 Perl Outline : Filehandles & File Tests Subroutines (functions) References passing arguments to functions nested data structure Packages/Modules Namespace/@INC VI, September 2008 Page 46

24 Perl namespace A namespace stores names (or identifiers), including names of variables, subroutines, filehandles, and formats. Each namespace has its own symbol table, which is basically a hash with a key for each identifier. Variables in different namespaces can even have the same name, but they are completely distinct from one another. The default namespace for programs is main. Each package starts with a package declaration. The package call takes one argument, the name of the package. Within the scope of a package declaration, all regular identifiers are created within that package (except for my variables). VI, September 2008 Page 47 / Export Perl locates modules by searching array (defined when Perl is built). When you refer to MyModule in your program, Perl searches in the directories listed for the module file MyModule.pm, and uses the first one it finds. VI, September 2008 Page 48

25 / Export To include a module in your program: require Module; use Module; The difference between use and require is that use pulls in the module at compile time. This means that functions like func1 or func2 can be used as predeclared list operators throughout the file. func1($a,$b); The require call does not necessarily load the module during compilation, so you must explicitly qualify its routines with the package name. Module::func1($a,$b); VI, September 2008 Page 49 / Export Animals.pm # two essential lines in a package require Exporter; = ('Exporter'); # inherits from Exporter Package # export by default = qw($cat %canis carnivore); # export on demand = qw($tiger); # variables & functions declaration... 1; User's script use Animals; # import symbols use Animals qw($cat $tiger); # import $tiger and $cat VI, September 2008 Page 50

26 Perl VI, September 2008 Page 51

... and run the script as /path/to/script.pl. Of course, it'll need to be executable first, so chmod 755 script.pl (under Unix).

... and run the script as /path/to/script.pl. Of course, it'll need to be executable first, so chmod 755 script.pl (under Unix). NAME DESCRIPTION What is Perl? perlintro -- a brief introduction and overview of Perl This document is intended to give you a quick overview of the Perl programming language, along with pointers to further

More information

Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc.

Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc. Subroutines Subroutines aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We ll just say Subroutines. "Functions" generally means built-in functions perldoc perlsub The Basics

More information

COMS 3101 Programming Languages: Perl. Lecture 2

COMS 3101 Programming Languages: Perl. Lecture 2 COMS 3101 Programming Languages: Perl Lecture 2 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl Lecture Outline Control Flow (continued) Input / Output Subroutines Concepts:

More information

Perl Scripting. Students Will Learn. Course Description. Duration: 4 Days. Price: $2295

Perl Scripting. Students Will Learn. Course Description. Duration: 4 Days. Price: $2295 Perl Scripting Duration: 4 Days Price: $2295 Discounts: We offer multiple discount options. Click here for more info. Delivery Options: Attend face-to-face in the classroom, remote-live or on-demand streaming.

More information

IT441. Network Services Administration. Data Structures: Arrays

IT441. Network Services Administration. Data Structures: Arrays IT441 Network Services Administration Data Structures: Arrays Data Types Remember there are three basic data types in Perl o Numeric o String o Boolean (Logical) I differentiate between data types and

More information

Scripting Languages Perl Basics. Course: Hebrew University

Scripting Languages Perl Basics. Course: Hebrew University Scripting Languages Perl Basics Course: 67557 Hebrew University אליוט יפה Jaffe Lecturer: Elliot FMTEYEWTK Far More Than Everything You've Ever Wanted to Know Perl Pathologically Eclectic Rubbish Lister

More information

1. Introduction. 2. Scalar Data

1. Introduction. 2. Scalar Data 1. Introduction What Does Perl Stand For? Why Did Larry Create Perl? Why Didn t Larry Just Use Some Other Language? Is Perl Easy or Hard? How Did Perl Get to Be So Popular? What s Happening with Perl Now?

More information

BIOS 546 Midterm March 26, Write the line of code that all Perl programs on biolinx must start with so they can be executed.

BIOS 546 Midterm March 26, Write the line of code that all Perl programs on biolinx must start with so they can be executed. 1. What values are false in Perl? BIOS 546 Midterm March 26, 2007 2. Write the line of code that all Perl programs on biolinx must start with so they can be executed. 3. How do you make a comment in Perl?

More information

Classnote for COMS6100

Classnote for COMS6100 Classnote for COMS6100 Yiting Wang 3 November, 2016 Today we learn about subroutines, references, anonymous and file I/O in Perl. 1 Subroutines in Perl First of all, we review the subroutines that we had

More information

COMS 3101 Programming Languages: Perl. Lecture 5

COMS 3101 Programming Languages: Perl. Lecture 5 COMS 3101 Programming Languages: Perl Lecture 5 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl Lecture Outline Packages & Modules Concepts: Subroutine references Symbolic

More information

Outline. CS3157: Advanced Programming. Feedback from last class. Last plug

Outline. CS3157: Advanced Programming. Feedback from last class. Last plug Outline CS3157: Advanced Programming Lecture #2 Jan 23 Shlomo Hershkop shlomo@cs.columbia.edu Feedback Introduction to Perl review and continued Intro to Regular expressions Reading Programming Perl pg

More information

IT441. Network Services Administration. Perl: File Handles

IT441. Network Services Administration. Perl: File Handles IT441 Network Services Administration Perl: File Handles Comment Blocks Perl normally treats lines beginning with a # as a comment. Get in the habit of including comments with your code. Put a comment

More information

Programming Perls* Objective: To introduce students to the perl language.

Programming Perls* Objective: To introduce students to the perl language. Programming Perls* Objective: To introduce students to the perl language. Perl is a language for getting your job done. Making Easy Things Easy & Hard Things Possible Perl is a language for easily manipulating

More information

COMS 3101 Programming Languages: Perl. Lecture 6

COMS 3101 Programming Languages: Perl. Lecture 6 COMS 3101 Programming Languages: Perl Lecture 6 Fall 2013 Instructor: Ilia Vovsha http://www.cs.columbia.edu/~vovsha/coms3101/perl Lecture Outline Concepts: Subroutine references Symbolic references Saving

More information

Hands-On Perl Scripting and CGI Programming

Hands-On Perl Scripting and CGI Programming Hands-On Course Description This hands on Perl programming course provides a thorough introduction to the Perl programming language, teaching attendees how to develop and maintain portable scripts useful

More information

Learning Perl Objects, References, and Modules

Learning Perl Objects, References, and Modules Learning Perl Objects, References, and Modules Randal L. Schwartz with Tom Phoenix HLuHB Darmstadt Illlllllllllllllllllllll 15760214 O'REILLY* Beijing Cambridge Farnham Koln Paris Sebastopol Taipei Tokyo

More information

Indian Institute of Technology Kharagpur. PERL Part II. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

Indian Institute of Technology Kharagpur. PERL Part II. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Indian Institute of Technology Kharagpur PERL Part II Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Kharagpur, INDIA Lecture 22: PERL Part II On completion, the student will be able

More information

Modularity and Reusability I. Functions and code reuse

Modularity and Reusability I. Functions and code reuse Modularity and Reusability I Functions and code reuse Copyright 2006 2009 Stewart Weiss On being efficient When you realize that a piece of Perl code that you wrote may be useful in future programs, you

More information

CS 230 Programming Languages

CS 230 Programming Languages CS 230 Programming Languages 09 / 16 / 2013 Instructor: Michael Eckmann Today s Topics Questions/comments? Continue Syntax & Semantics Mini-pascal Attribute Grammars More Perl A more complex grammar Let's

More information

Beginning Perl. Third Edition. Apress. JAMES LEE with SIMON COZENS

Beginning Perl. Third Edition. Apress. JAMES LEE with SIMON COZENS Beginning Perl Third Edition JAMES LEE with SIMON COZENS Apress About the Author... About the Technical Reviewers Acknowledgements Suitrod yetion «. xvi xvii xviii «xix. Chapter 1: First Steps in Perl..

More information

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list.

They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list. Arrays Perl arrays store lists of scalar values, which may be of different types. They grow as needed, and may be made to shrink. Officially, a Perl array is a variable whose value is a list. A list literal

More information

T-( )-MALV, Natural Language Processing The programming language Perl

T-( )-MALV, Natural Language Processing The programming language Perl T-(538 725)-MALV, Natural Language Processing The programming language Perl Hrafn Loftsson 1 Hannes Högni Vilhjálmsson 1 1 School of Computer Science, Reykjavik University September 2010 Outline 1 Perl

More information

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration IT441 Network Services Administration Subroutines DRAFT (a.k.a., Functions, Methods, etc.) Organizing Code We have recently discussed the topic of organizing data (i.e., arrays and hashes) in order to

More information

print STDERR "This is a debugging message.\n";

print STDERR This is a debugging message.\n; NAME DESCRIPTION perlopentut - simple recipes for opening files and pipes in Perl Whenever you do I/O on a file in Perl, you do so through what in Perl is called a filehandle. A filehandle is an internal

More information

(Refer Slide Time: 01:12)

(Refer Slide Time: 01:12) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #22 PERL Part II We continue with our discussion on the Perl

More information

CHAPTER 2. Troubleshooting CGI Scripts

CHAPTER 2. Troubleshooting CGI Scripts CHAPTER 2 Troubleshooting CGI Scripts OVERVIEW Web servers and their CGI environment can be set up in a variety of ways. Chapter 1 covered the basics of the installation and configuration of scripts. However,

More information

@EXPORT_OK = qw(munge frobnicate); # symbols to export on request

@EXPORT_OK = qw(munge frobnicate); # symbols to export on request NAME Exporter - Implements default import method for modules SYNOPSIS In module YourModule.pm: package YourModule; require Exporter; @ISA = qw(exporter); @EXPORT_OK = qw(munge frobnicate); # symbols to

More information

PERL Scripting - Course Contents

PERL Scripting - Course Contents PERL Scripting - Course Contents Day - 1 Introduction to PERL Comments Reading from Standard Input Writing to Standard Output Scalar Variables Numbers and Strings Use of Single Quotes and Double Quotes

More information

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1 CSCI 4152/6509 Natural Language Processing Perl Tutorial CSCI 4152/6509 Vlado Kešelj CSCI 4152/6509, Perl Tutorial 1 created in 1987 by Larry Wall About Perl interpreted language, with just-in-time semi-compilation

More information

Environment Variables

Environment Variables Environment Variables > the shell has variables: my_var="some_value" > no space allowed around "=" echo $my_var > dereferencing by prepending a "$" > more generally: ${my_var} > shell variables can be

More information

package YourModule; require = = qw(munge frobnicate); # symbols to export on request

package YourModule; require = = qw(munge frobnicate); # symbols to export on request NAME SYNOPSIS Exporter - Implements default import method for modules In module YourModule.pm: require Exporter; @EXPORT_OK = qw(munge frobnicate); # symbols to export on request or use Exporter 'import';

More information

PERL Bioinformatics. Nicholas E. Navin, Ph.D. Department of Genetics Department of Bioinformatics. TA: Dr. Yong Wang

PERL Bioinformatics. Nicholas E. Navin, Ph.D. Department of Genetics Department of Bioinformatics. TA: Dr. Yong Wang PERL Bioinformatics Nicholas E. Navin, Ph.D. Department of Genetics Department of Bioinformatics TA: Dr. Yong Wang UNIX Background and History PERL Practical Extraction and Reporting Language Developed

More information

Systems Skills in C and Unix

Systems Skills in C and Unix 15-123 Systems Skills in C and Unix Plan Perl programming basics Operators loops, arrays, conditionals file processing subroutines, references Systems programming Command line arguments Perl intro Unix

More information

Parallelizing data processing on cluster nodes with the Distributor

Parallelizing data processing on cluster nodes with the Distributor Parallelizing data processing on cluster nodes with the Distributor Andreas Bernauer February 20, 2004 1 Introduction This article describes how to use the Perl module Distributor.pm with its counterpart

More information

The Perl Debugger. Avoiding Bugs with Warnings and Strict. Daniel Allen. Abstract

The Perl Debugger. Avoiding Bugs with Warnings and Strict. Daniel Allen. Abstract 1 of 8 6/18/2006 7:36 PM The Perl Debugger Daniel Allen Abstract Sticking in extra print statements is one way to debug your Perl code, but a full-featured debugger can give you more information. Debugging

More information

A Field Guide To The Perl Command Line. Andy Lester

A Field Guide To The Perl Command Line. Andy Lester A Field Guide To The Perl Command Line Andy Lester andy@petdance.com http://petdance.com/perl/ Where we're going Command-line == super lazy The magic filehandle The -e switch -p, -n: Implicit looping -a,

More information

Regular expressions and case insensitivity

Regular expressions and case insensitivity Regular expressions and case insensitivity As previously mentioned, you can make matching case insensitive with the i flag: /\b[uu][nn][ii][xx]\b/; /\bunix\b/i; # explicitly giving case folding # using

More information

Perl. Many of these conflict with design principles of languages for teaching.

Perl. Many of these conflict with design principles of languages for teaching. Perl Perl = Practical Extraction and Report Language Developed by Larry Wall (late 80 s) as a replacement for awk. Has grown to become a replacement for awk, sed, grep, other filters, shell scripts, C

More information

Bioinformatics. Computational Methods II: Sequence Analysis with Perl. George Bell WIBR Biocomputing Group

Bioinformatics. Computational Methods II: Sequence Analysis with Perl. George Bell WIBR Biocomputing Group Bioinformatics Computational Methods II: Sequence Analysis with Perl George Bell WIBR Biocomputing Group Sequence Analysis with Perl Introduction Input/output Variables Functions Control structures Arrays

More information

Perl for Biologists. Session 9 April 29, Subroutines and functions. Jaroslaw Pillardy

Perl for Biologists. Session 9 April 29, Subroutines and functions. Jaroslaw Pillardy Perl for Biologists Session 9 April 29, 2015 Subroutines and functions Jaroslaw Pillardy Perl for Biologists 1.2 1 Suggestions Welcomed! There are three more sessions devoted to practical examples They

More information

Introduction to Perl. c Sanjiv K. Bhatia. Department of Mathematics & Computer Science University of Missouri St. Louis St.

Introduction to Perl. c Sanjiv K. Bhatia. Department of Mathematics & Computer Science University of Missouri St. Louis St. Introduction to Perl c Sanjiv K. Bhatia Department of Mathematics & Computer Science University of Missouri St. Louis St. Louis, MO 63121 Contents 1 Introduction 1 2 Getting started 1 3 Writing Perl scripts

More information

A Crash Course in Perl5

A Crash Course in Perl5 z e e g e e s o f t w a r e A Crash Course in Perl5 Part 5: Data Zeegee Software Inc. http://www.zeegee.com/ Terms and Conditions These slides are Copyright 2008 by Zeegee Software Inc. They have been

More information

CS 105 Perl: Completing the Toolbox

CS 105 Perl: Completing the Toolbox CS 105 Perl: Completing the Toolbox March 4, 2013 Agenda autodie with open Inspecting scalars perl -c Unary coercion Topicalization ~~ Unique list idiom Schwartzian Transform Using // for defaults and

More information

More Perl. CS174 Chris Pollett Oct 25, 2006.

More Perl. CS174 Chris Pollett Oct 25, 2006. More Perl CS174 Chris Pollett Oct 25, 2006. Outline Loops Arrays Hashes Functions Selection Redux Last day we learned about how if-else works in Perl. Perl does not have a switch statement Like Javascript,

More information

Perl Primer An Introduction to Perl for C++ Programmers by Frank McCown and Tim Baird Harding University

Perl Primer An Introduction to Perl for C++ Programmers by Frank McCown and Tim Baird Harding University Perl Primer An Introduction to Perl for C++ Programmers by Frank McCown and Tim Baird Harding University PERL is the Practical Extraction and Report Language (or Pathologically Eclectic Rubbish Lister)

More information

Perl Programming Fundamentals for the Computational Biologist

Perl Programming Fundamentals for the Computational Biologist Perl Programming Fundamentals for the Computational Biologist Class 2 Marine Biological Laboratory, Woods Hole Advances in Genome Technology and Bioinformatics Fall 2004 Andrew Tolonen Chisholm lab, MIT

More information

Pod::Usage, pod2usage() - print a usage message from embedded pod documentation

Pod::Usage, pod2usage() - print a usage message from embedded pod documentation NAME Pod::Usage, pod2usage() - print a usage message from embedded pod documentation SYNOPSIS use Pod::Usage my $message_text = "This text precedes the usage message."; my $exit_status = 2; ## The exit

More information

UNIX Shell Programming

UNIX Shell Programming $!... 5:13 $$ and $!... 5:13.profile File... 7:4 /etc/bashrc... 10:13 /etc/profile... 10:12 /etc/profile File... 7:5 ~/.bash_login... 10:15 ~/.bash_logout... 10:18 ~/.bash_profile... 10:14 ~/.bashrc...

More information

Pathologically Eclectic Rubbish Lister

Pathologically Eclectic Rubbish Lister Pathologically Eclectic Rubbish Lister 1 Perl Design Philosophy Author: Reuben Francis Cornel perl is an acronym for Practical Extraction and Report Language. But I guess the title is a rough translation

More information

CS 11 Ocaml track: lecture 3

CS 11 Ocaml track: lecture 3 CS 11 Ocaml track: lecture 3 n Today: n A (large) variety of odds and ends n Imperative programming in Ocaml Equality/inequality operators n Two inequality operators: and!= n Two equality operators:

More information

: the User (owner) for this file (your cruzid, when you do it) Position: directory flag. read Group.

: the User (owner) for this file (your cruzid, when you do it) Position: directory flag. read Group. CMPS 12L Introduction to Programming Lab Assignment 2 We have three goals in this assignment: to learn about file permissions in Unix, to get a basic introduction to the Andrew File System and it s directory

More information

CSCI 4152/6509 Natural Language Processing Lecture 6: Regular Expressions; Text Processing in Perl

CSCI 4152/6509 Natural Language Processing Lecture 6: Regular Expressions; Text Processing in Perl Lecture 6 p.1 Faculty of Computer Science, Dalhousie University CSCI 4152/6509 Natural Language Processing Lecture 6: Regular Expressions; Text Processing in Perl 18-Jan-2019 Location: LSC Psychology P5260

More information

CSC105, Introduction to Computer Science I. Introduction. Perl Directions NOTE : It is also a good idea to

CSC105, Introduction to Computer Science I. Introduction. Perl Directions NOTE : It is also a good idea to CSC105, Introduction to Computer Science Lab03: Introducing Perl I. Introduction. [NOTE: This material assumes that you have reviewed Chapters 1, First Steps in Perl and 2, Working With Simple Values in

More information

Perl. Perl. Perl. Which Perl

Perl. Perl. Perl. Which Perl Perl Perl Perl = Practical Extraction and Report Language Developed by Larry Wall (late 80 s) as a replacement for awk. Has grown to become a replacement for awk, sed, grep, other filters, shell scripts,

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 9/20/2013 Context and Modules (Perl) Scripting as Glue 1 Outline Programming in the large Scripting as glue 2 Modules Module = file p/q.pm that starts with declaration

More information

CSC UNIX System, Spring 2015

CSC UNIX System, Spring 2015 CSC 352 - UNIX System, Spring 2015 Study guide for the CSC352 midterm exam (20% of grade). Dr. Dale E. Parson, http://faculty.kutztown.edu/parson We will have a midterm on March 19 on material we have

More information

Processes and Shells

Processes and Shells Shell ls pico httpd CPU Kernel Disk NIC Processes Processes are tasks run by you or the OS. Processes can be: shells commands programs daemons scripts Shells Processes operate in the context of a shell.

More information

Week January 27 January. From last week Arrays. Reading for this week Hashes. Files. 24 H: Hour 4 PP Ch 6:29-34, Ch7:51-52

Week January 27 January. From last week Arrays. Reading for this week Hashes. Files. 24 H: Hour 4 PP Ch 6:29-34, Ch7:51-52 Week 3 23 January 27 January From last week Arrays 24 H: Hour 4 PP Ch 6:29-34, Ch7:51-52 Reading for this week Hashes 24 H: Hour 7 PP Ch 6:34-37 Files 24 H: Hour 5 PP Ch 19: 163-169 Biol 59500-033 - Practical

More information

runs all the testscripts named as arguments and checks standard output for the expected strings in TAP format.

runs all the testscripts named as arguments and checks standard output for the expected strings in TAP format. NAME VERSION SYNOPSIS Test::Harness - Run Perl standard test scripts with statistics Version 2.64 DESCRIPTION Taint mode use Test::Harness; runtests(@test_files); STOP! If all you want to do is write a

More information

CMSC 331 Final Exam Fall 2013

CMSC 331 Final Exam Fall 2013 CMSC 331 Final Exam Fall 2013 Name: UMBC username: You have two hours to complete this closed book exam. Use the backs of these pages if you need more room for your answers. Describe any assumptions you

More information

UNIX System Programming Lecture 3: BASH Programming

UNIX System Programming Lecture 3: BASH Programming UNIX System Programming Outline Filesystems Redirection Shell Programming Reference BLP: Chapter 2 BFAQ: Bash FAQ BMAN: Bash man page BPRI: Bash Programming Introduction BABS: Advanced Bash Scripting Guide

More information

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes Overview For this lab, you will use: one or more of the conditional statements explained below

More information

Introduction to Shell Scripting

Introduction to Shell Scripting Introduction to Shell Scripting Evan Bollig and Geoffrey Womeldorff Presenter Yusong Liu 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

More information

Introduction Variables Helper commands Control Flow Constructs Basic Plumbing. Bash Scripting. Alessandro Barenghi

Introduction Variables Helper commands Control Flow Constructs Basic Plumbing. Bash Scripting. Alessandro Barenghi Bash Scripting Alessandro Barenghi Dipartimento di Elettronica, Informazione e Bioingegneria Politecnico di Milano alessandro.barenghi - at - polimi.it April 28, 2015 Introduction The bash command shell

More information

A control expression must evaluate to a value that can be interpreted as true or false.

A control expression must evaluate to a value that can be interpreted as true or false. Control Statements Control Expressions A control expression must evaluate to a value that can be interpreted as true or false. How a control statement behaves depends on the value of its control expression.

More information

Learning Perl 6. brian d foy, Version 0.6, Nordic Perl Workshop 2007

Learning Perl 6. brian d foy, Version 0.6, Nordic Perl Workshop 2007 Learning Perl 6 brian d foy, Version 0.6, Nordic Perl Workshop 2007 for the purposes of this tutorial Perl 5 never existed Don t really do this $ ln -s /usr/local/bin/pugs /usr/bin/perl

More information

Perl. Interview Questions and Answers

Perl. Interview Questions and Answers and Answers Prepared by Abhisek Vyas Document Version 1.0 Team, www.sybaseblog.com 1 of 13 Q. How do you separate executable statements in perl? semi-colons separate executable statements Example: my(

More information

A shell can be used in one of two ways:

A shell can be used in one of two ways: Shell Scripting 1 A shell can be used in one of two ways: A command interpreter, used interactively A programming language, to write shell scripts (your own custom commands) 2 If we have a set of commands

More information

APPENDIX B. The Future Of Perl & CGI Programming OVERVIEW

APPENDIX B. The Future Of Perl & CGI Programming OVERVIEW APPENDIX B The Future Of Perl & CGI Programming OVERVIEW Although Perl 5 has been available for quite a while now, not many CGI authors have taken advantage of Perl 5 specific features. There are several

More information

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash CS 25200: Systems Programming Lecture 10: Shell Scripting in Bash Dr. Jef Turkstra 2018 Dr. Jeffrey A. Turkstra 1 Lecture 10 Getting started with Bash Data types Reading and writing Control loops Decision

More information

Assignment clarifications

Assignment clarifications Assignment clarifications How many errors to print? at most 1 per token. Interpretation of white space in { } treat as a valid extension, involving white space characters. Assignment FAQs have been updated.

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to A PROGRAM IS A SEQUENCE of instructions that a computer can execute to perform some task. A simple enough idea, but for the computer to make any use of the instructions, they must be written in a form

More information

Script Programming Systems Skills in C and Unix

Script Programming Systems Skills in C and Unix Script Programming with Perl II 15-123 Systems Skills in C and Unix Subroutines sub sum { return $a + $b; } So we can call this as: $a = 12; $b = 10; $sum = sum(); print the sum is $sum\n ; Passing Arguments

More information

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1 Shell Scripting Todd Kelley kelleyt@algonquincollege.com CST8207 Todd Kelley 1 If we have a set of commands that we want to run on a regular basis, we could write a script A script acts as a Linux command,

More information

Object-Oriented-Programming! (OOP)

Object-Oriented-Programming! (OOP) Object-Oriented-Programming! (OOP) Basically it s all about abstraction & information hiding n Good programs consist of layer upon layer of reusable code (think of software tools). n The programmer should

More information

Recreates the Perl source, making an attempt to format it coherently. Status: 8 (it works nicely, but a few obscure things are missing).

Recreates the Perl source, making an attempt to format it coherently. Status: 8 (it works nicely, but a few obscure things are missing). NAME DESCRIPTION perlcompile - Introduction to the Perl Compiler-Translator Perl has always had a compiler: your source is compiled into an internal form (a parse tree) which is then optimized before being

More information

Bamuengine.com. Chapter 14. Perl The Mater Manipulator

Bamuengine.com. Chapter 14. Perl The Mater Manipulator Chapter 14. Perl The Mater Manipulator Introduciton The following sections tell you what Perl is, the variables and operators in perl, the string handling functions. The chapter also discusses file handling

More information

Week Overview. Simple filter commands: head, tail, cut, sort, tr, wc grep utility stdin, stdout, stderr Redirection and piping /dev/null file

Week Overview. Simple filter commands: head, tail, cut, sort, tr, wc grep utility stdin, stdout, stderr Redirection and piping /dev/null file ULI101 Week 05 Week Overview Simple filter commands: head, tail, cut, sort, tr, wc grep utility stdin, stdout, stderr Redirection and piping /dev/null file head and tail commands These commands display

More information

Bashed One Too Many Times. Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009

Bashed One Too Many Times. Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009 Bashed One Too Many Times Features of the Bash Shell St. Louis Unix Users Group Jeff Muse, Jan 14, 2009 What is a Shell? The shell interprets commands and executes them It provides you with an environment

More information

Programming Style Guide v1.1

Programming Style Guide v1.1 Oregon State University Intro to programming Source Code Style Guide Modified from: OREGON INSTITUTE OF TECHNOLOGY COMPUTER SYSTEMS ENGINEERING TECHNOLOGY Modified by: Joseph Jess Programming Style Guide

More information

COMS 6100 Class Notes 3

COMS 6100 Class Notes 3 COMS 6100 Class Notes 3 Daniel Solus September 1, 2016 1 General Remarks The class was split into two main sections. We finished our introduction to Linux commands by reviewing Linux commands I and II

More information

Introduction to Perl. Perl Background. Sept 24, 2007 Class Meeting 6

Introduction to Perl. Perl Background. Sept 24, 2007 Class Meeting 6 Introduction to Perl Sept 24, 2007 Class Meeting 6 * Notes on Perl by Lenwood Heath, Virginia Tech 2004 Perl Background Practical Extraction and Report Language (Perl) Created by Larry Wall, mid-1980's

More information

SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7

SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7 SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7 Hi everyone once again welcome to this lecture we are actually the course is Linux programming and scripting we have been talking about the Perl, Perl

More information

Object Oriented Programming and Perl

Object Oriented Programming and Perl Object Oriented Programming and Perl Prog for Biol 2011 Simon Prochnik 1 Why do we teach you about objects and object-oriented programming (OOP)? Objects and OOP allow you to use other people s code to

More information

Intermediate Perl Table of Contents Intermediate Perl Foreword Preface Structure of This Book Conventions Used in This Book Using Code Examples

Intermediate Perl Table of Contents Intermediate Perl Foreword Preface Structure of This Book Conventions Used in This Book Using Code Examples Intermediate Perl Table of Contents Intermediate Perl Foreword Preface Structure of This Book Conventions Used in This Book Using Code Examples Comments and Questions Safari Enabled Acknowledgments Chapter

More information

Regular expressions and case insensitivity

Regular expressions and case insensitivity Regular expressions and case insensitivity As previously mentioned, you can make matching case insensitive with the i flag: /\b[uu][nn][ii][xx]\b/; # explicitly giving case folding /\bunix\b/i; # using

More information

CSCI-GA Scripting Languages

CSCI-GA Scripting Languages CSCI-GA.3033.003 Scripting Languages 9/11/2013 Textual data processing (Perl) 1 Announcements If you did not get a PIN to enroll, contact Stephanie Meik 2 Outline Perl Basics (continued) Regular Expressions

More information

package owner, which is probably not what you meant. Use braces to disambiguate, as in "This is ${owner} s house". :: '

package owner, which is probably not what you meant. Use braces to disambiguate, as in This is ${owner} s house. :: ' NAME DESCRIPTION Packages perlmod - Perl modules (packages and symbol tables) Perl provides a mechanism for alternative namespaces to protect packages from stomping on each other's variables. In fact,

More information

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi Titolo presentazione Piattaforme Software per la Rete sottotitolo BASH Scripting Milano, XX mese 20XX A.A. 2016/17, Alessandro Barenghi Outline 1) Introduction to BASH 2) Helper commands 3) Control Flow

More information

Perl Tutorial. Diana Inkpen. School of Information Technology and Engineering University of Ottawa. CSI 5180, Fall 2004

Perl Tutorial. Diana Inkpen. School of Information Technology and Engineering University of Ottawa. CSI 5180, Fall 2004 Perl Tutorial Diana Inkpen School of Information Technology and Engineering University of Ottawa CSI 5180, Fall 2004 1 What is Perl Practical Extraction and Report Language. Created, implemented, maintained

More information

Perl Library Functions

Perl Library Functions Perl Library Functions Perl has literally hundreds of functions for all kinds of purposes: file manipulation, database access, network programming, etc. etc. It has an especially rich collection of functions

More information

CSE 390a Lecture 2. Exploring Shell Commands, Streams, and Redirection

CSE 390a Lecture 2. Exploring Shell Commands, Streams, and Redirection 1 CSE 390a Lecture 2 Exploring Shell Commands, Streams, and Redirection slides created by Marty Stepp, modified by Jessica Miller & Ruth Anderson http://www.cs.washington.edu/390a/ 2 Lecture summary Unix

More information

Chapter 1 - Introduction. September 8, 2016

Chapter 1 - Introduction. September 8, 2016 Chapter 1 - Introduction September 8, 2016 Introduction Overview of Linux/Unix Shells Commands: built-in, aliases, program invocations, alternation and iteration Finding more information: man, info Help

More information

Perl for Biologists. Session 6 April 16, Files, directories and I/O operations. Jaroslaw Pillardy

Perl for Biologists. Session 6 April 16, Files, directories and I/O operations. Jaroslaw Pillardy Perl for Biologists Session 6 April 16, 2014 Files, directories and I/O operations Jaroslaw Pillardy Perl for Biologists 1.1 1 Reminder: What is a Hash? Array Hash Index Value Key Value 0 apple red fruit

More information

Sequence Analysis with Perl. Unix, Perl and BioPerl. Why Perl? Objectives. A first Perl program. Perl Input/Output. II: Sequence Analysis with Perl

Sequence Analysis with Perl. Unix, Perl and BioPerl. Why Perl? Objectives. A first Perl program. Perl Input/Output. II: Sequence Analysis with Perl Sequence Analysis with Perl Unix, Perl and BioPerl II: Sequence Analysis with Perl George Bell, Ph.D. WIBR Bioinformatics and Research Computing Introduction Input/output Variables Functions Control structures

More information

bash Execution Control COMP2101 Winter 2019

bash Execution Control COMP2101 Winter 2019 bash Execution Control COMP2101 Winter 2019 Bash Execution Control Scripts commonly can evaluate situations and make simple decisions about actions to take Simple evaluations and actions can be accomplished

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

Lecture 5/6: Scripting and Perl

Lecture 5/6: Scripting and Perl Lecture 5/6: Scripting and Perl COMP 524 Programming Language Concepts Stephen Olivier January 29, 2009 and February 3, 2009 Based on notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goal of Lecture

More information

Unix, Perl and BioPerl

Unix, Perl and BioPerl Unix, Perl and BioPerl II: Sequence Analysis with Perl George Bell, Ph.D. WIBR Bioinformatics and Research Computing Sequence Analysis with Perl Introduction Input/output Variables Functions Control structures

More information