Llama to Ram How to think like a perl weenie Rob Napier 3/18/99.

Slides:



Advertisements
Similar presentations
A Guide to Unix Using Linux Fourth Edition
Advertisements

Adv. UNIX:Perl/81 Advanced UNIX v Objectives of these slides: –introduce Perl (version ) –mostly based on Chapter 1, Learning Perl
Programming Perls* Objective: To introduce students to the perl language. –Perl is a language for getting your job done. –Making Easy Things Easy & Hard.
CSET4100 – Fall 2009 Perl Introduction Scalar Data, Operators & Control Blocks Acknowledgements: Slides adapted from NYU Computer Science course on UNIX.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
I/O while ($line= ){ #remove new line char \n chomp($line); if($line eq “quit”){ exit(1); } while ( ){ #remove new line char \n chomp($_); if($_ eq “quit”){
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
Guide To UNIX Using Linux Third Edition
Objected Oriented Perl An introduction – because I don’t have the time or patience for an in- depth OOP lecture series…
Subroutines. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We’ll just say Subroutines. –“Functions” generally means built-in.
Introduction to Perl Part III By: Cedric Notredame Adapted from (BT McInnes)
Introduction to Perl & BioPerl Dr G. P. S. Raghava Bioinformatics Centre Bioinformatics Centre IMTECH, Chandigarh Web:
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Chapter 5 Bourne Shells Scripts By C. Shing ITEC Dept Radford University.
An Introduction to Unix Shell Scripting
Perl Refernces. Kinds of references: hard: a scalar variable that points to data symbolic: a variable that names another reference typeglob: a kind of.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
Control Structures. Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Perl Practical(?)‏ Extraction and Report Language.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Sed, awk, & perl CS 2204 Class meeting 13 *Notes by Mir Farooq Ali and other members of the CS faculty at Virginia Tech. Copyright 2003.
Introduction to Perl Yupu Liang cbio at MSKCC
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Introduction to Perl Part III By: Bridget Thomson McInnes 6 Feburary 2004.
7 1 User-Defined Functions CGI/Perl Programming By Diane Zak.
Programming in Perl predefined variables Peter Verhás January 2002.
Introduction to Programming the WWW I CMSC Winter 2003.
Introduction to Perl “Practical Extraction and Report Language” “Pathologically Eclectic Rubbish Lister”
5 1 Data Files CGI/Perl Programming By Diane Zak.
Searching and Sorting. Why Use Data Files? There are many cases where the input to the program may come from a data file.Using data files in your programs.
Programming Perl in UNIX Course Number : CIT 370 Week 6 Prof. Daniel Chen.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Perl Basics. sh-bang !!!! Every perl program starts with a sh-bang line #!/usr/bin/perl # hello.pl printf “Hello, world!\n”; printf STDOUT “Hello, world!\n”;
Perl Chapter 5 Hashes. Outside of world of Perl, know as associative arrays Also called hash tables Perl one of few languages that has hashes built-in.
Perl Chapter 6 Functions. Subprograms In Perl, all subprograms are functions – returns 0 or 1 value – although may have “side-effects” optional function.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
Chapter Twelve sed, awk & perl1 System Programming sed, awk & perl.
Getting started in Perl: Intro to Perl for programmers Matthew Heusser – xndev.com - Presented to the West Michigan Perl User’s Group.
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
A Few More Functions. One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. –no interpolation.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
 2001 Prentice Hall, Inc. All rights reserved. Chapter 7 - Introduction to Common Gateway Interface (CGI) Outline 7.1Introduction 7.2A Simple HTTP Transaction.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Scripting Languages ● Perl, Python, Unix Shell, VB, JavaScript, etc. ● Glue Languages. ● Typeless. ● Interchangeable Code and Data. ● Interpreted vs. Compiled.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
2000 Copyrights, Danielle S. Lahmani Foreach example = ( 3, 5, 7, 9) foreach $one ) { $one*=3; } is now (9,15,21,27)
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Camel –perldoc perlop Many operators have numeric and string version –remember Perl will.
Programming in Perl references and objects Peter Verhás January 2002.
Perl Ed Finegan. Overview of Pearl Perl is a high-level programming language written by Larry Wall. It derives from the C programming language and to.
Regular Expressions Copyright Doug Maxwell (
Exceptions Lightning Talk on Exceptions MiltonKeynes.pm 12-Jan-2009
Lesson 2. Control structures File IO - reading and writing Subroutines
Programming Perls* Objective: To introduce students to the perl language. Perl is a language for getting your job done. Making Easy Things Easy & Hard.
CSE 303 Concepts and Tools for Software Development
Subroutines.
Presentation transcript:

Llama to Ram How to think like a perl weenie Rob Napier 3/18/99

Llama to Ram -- Rob Napier2 Introduction n In this talk we will move from the basics of perl syntax and grammar (Llama) to the philosophy behind perl and the tools of the trade (Ram). n This talk will not cover many advanced perl topics, and in particular won't cover performance issues or advanced data structures

3/18/99Llama to Ram -- Rob Napier3 Topics of Discussion n Background and philosophy n Perl basics n Tools of the trade n Pitfalls n Perl rules n Gotchas

3/18/99Llama to Ram -- Rob Napier4 Background and Philosophy n Quotes n Influences n O’Reilly Bestiary

3/18/99Llama to Ram -- Rob Napier5 Quotes n Practical Extraction and Report Language n Perl is a language for getting things done. n There’s more than one way to do it

3/18/99Llama to Ram -- Rob Napier6 Major Influences n C n sh n regex n unix n LISP and COBOL

3/18/99Llama to Ram -- Rob Napier7 O’Reilly Bestiary n Learning - Llama n Programming - Camel n Cookbook - Ram n Advanced - Leopard/Panther n Also Perl/Tk, Nutshell, Win32, and others

3/18/99Llama to Ram -- Rob Napier8 Perl Basics n Auto-conversion (coercion) n The search for Truth n Safety nets n Data types

3/18/99Llama to Ram -- Rob Napier9 Auto-conversion (coercion) n Strings Numbers n References => Strings n undef => Strings n Scalars => Lists n Lists => Scalar u The dreaded 1’s

3/18/99Llama to Ram -- Rob Napier10 The Search for Truth n False: “”, “0” u False = 0, undef, () u True = 1, ref, “0 but true”, and most anything else

3/18/99Llama to Ram -- Rob Napier11 Safety Nets n -w n use strict

3/18/99Llama to Ram -- Rob Napier12 Data types n Scalars n Lists n Hashes n Filehandles n References

3/18/99Llama to Ram -- Rob Napier13 Scalars n Numbers n Strings n References n undef n Typeglob n Filehandle $foo = “bar”;

3/18/99Llama to Ram -- Rob Napier14 Lists n Heterogeneous n Both list-like and array-like, but usually = qw(bar baz bang); 6];

3/18/99Llama to Ram -- Rob Napier15 Hashes n Associate arrays n keys, values, each, delete, exists %foo = (apple => “red”, orange => “orange”, foo => 2); $foo{apple} = orange};

3/18/99Llama to Ram -- Rob Napier16 Filehandles n open (FOO, “foo”); n while ( ) { n while (<>) { n Includes predefined STDOUT, STDIN, STDERR

3/18/99Llama to Ram -- Rob Napier17 Typeglobs n Entries in the symbols table n Not used very often except for references to filehandles

3/18/99Llama to Ram -- Rob Napier18 References n Hard n Symbolic

3/18/99Llama to Ram -- Rob Napier19 Hard References n Similar to C-style pointers. $scalarref = \$foo; $arrayref = $hashref = \%ENV; $coderef = \&handler; $globref = \*foo; $scalarref = \1; $arrayref = [1, 2, [‘a’, ‘b’, ‘c’]]; $hashref = {‘Adam’ => ‘Eve’, ‘Clyde’ => Bonnie’ }; $coderef = sub {print “Boink!\n” };

3/18/99Llama to Ram -- Rob Napier20 Symbolic References n Indirect references to variable n These can be very dangerous (and aren’t allowed under ‘use strict’) n $$scalarref; n %$hashref

3/18/99Llama to Ram -- Rob Napier21 Tools of the trade n Lists n Hashes n Regex n Subs n Modules

3/18/99Llama to Ram -- Rob Napier22 Lists n Usually used as lists, instead of arrays n qw() n Sets n Slurping

3/18/99Llama to Ram -- Rob Napier23 Lists, seldom arrays n Usually use foreach, rather than subscripting into arrays. Instead of: for ($i =0; $i <= $#list; $i++) { do_something($list[$i]); } Do this: foreach $elem { do_something($_); }

3/18/99Llama to Ram -- Rob Napier24 qw() n Very good way to set lists of quoted = qw(this is a test);

3/18/99Llama to Ram -- Rob Napier25 = (); foreach { $count{$e}++ } foreach $e (keys %count) { $e); $count{$e} == 2 ? : }, $e; }

3/18/99Llama to Ram -- Rob Napier26 Slurping n Often it’s handy to just slurp a whole file and work on it in memory: open(FOO, = ;

3/18/99Llama to Ram -- Rob Napier27 Hashes n Swiss-army knife of perl u Associative arrays u Records u “In list” applications

3/18/99Llama to Ram -- Rob Napier28 Associate Arrays %foo = (apple => “red”, orange => “orange”); print $foo{apple};

3/18/99Llama to Ram -- Rob Napier29 Records The hard = getpwuid($<); %user = (name => $entry[0], passwd => $entry[1], uid => $entry[2], gid => $entry[3], quota => $entry[4], comment => $entry[5], […], expire => $entry[9]); print “name is $user{name}\n”;

3/18/99Llama to Ram -- Rob Napier30 Records cont The easy way (i.e. the perl = qw(name passwd uid gid quota comment gcos dir shell expire); = getpwuid $<; print “name is $user{name}\n”;

3/18/99Llama to Ram -- Rob Napier31 “In list” applications n Maintaining list order sub unique { my = my %seen = (); # Hash to keep track of what we've seen my $item; # Current item # Unique list foreach $item { push $item) unless $seen{$item}++; } }

3/18/99Llama to Ram -- Rob Napier32 “In list” applications cont n Trashing list order sub unique { my = my %uniq; = (); return }

3/18/99Llama to Ram -- Rob Napier33 Regex n Very useful for getting a lot of things done fast. Rob Napier: 9408 Erinsbrook Drive, Raleigh, NC (919) /(.*):\s*([^,]*),\s*([^,]*),\s*(\w+)\s+(\d+)\s+(?=\()(.*)/ $name = $1; $address = $2; $city = $3; $state = $4; $zip = $5; $phone = $6;

3/18/99Llama to Ram -- Rob Napier34 Subs n Passing non-scalars n Returning non-scalars n Named parameters

3/18/99Llama to Ram -- Rob Napier35 Passing non-scalars n Try to move non-scalar to the end n If you can’t, pass a reference sub foo { print print }

3/18/99Llama to Ram -- Rob Napier36 Returning non-scalars n If you can return it as a flat list (or hash), then just return it. n If you have multiple, distinct return values, return a list of references sub foo { = qw(this is a test); = qw(this is a test); return }

3/18/99Llama to Ram -- Rob Napier37 Named parameters sub thefunc { my %args = ( INCREMENT => '10s', FINISH => 0, START => # argument pair list goes here ); if ($args{INCREMENT} =~ /m$/ ) {..... } } thefunc(INCREMENT => "20s", START => "+5m", FINISH => "+30m");

3/18/99Llama to Ram -- Rob Napier38 Modules n File::Path n File::Find n File::Copy n Exporter n getop n sendmail n CGI n Cwd

3/18/99Llama to Ram -- Rob Napier39 perl4 pitfalls n use strict! (and debatably also use -w) n local => my n chop => chomp n require => use n Avoid globals n Avoid typeglobs n Investigate complex data structures

3/18/99Llama to Ram -- Rob Napier40 sh pitfalls n use strict! n << instead of multiple prints n 0=false, 1=true except on system calls n Don’t over-fork. Most of what you want is in perl: rm/rm -rf, find, ls, echo, grep, awk, sed, pwd, mkdir, mkdir -p, chown, chgrp, cp, ln n Avoid globals

3/18/99Llama to Ram -- Rob Napier41 sh pitfalls (cont) n Don’t store lists as strings n Avoid temp files n Avoid excessive chdir()

3/18/99Llama to Ram -- Rob Napier42 C pitfalls n Avoid subscripting lists that you’re iterating over n printf -> print n Don’t fear labels, especially for using ‘last’ and ‘next’ n Don’t try to split a string character by character. Use regex. n Don’t overlook POSIX

3/18/99Llama to Ram -- Rob Napier43 General perl pitfalls n Generally you don’t need to add.pl onto script names. n Often readdir() is a better tool than glob() n tr/a-z/A-Z/ -> uc()

3/18/99Llama to Ram -- Rob Napier44 Perl rules n Always return() n Always check your system return codes and close() returns n use strict n $# => scalar (or scalar context) u Some people may debate this one, but I find it helps a lot. n Before writing anything complex, always check CPAN (

3/18/99Llama to Ram -- Rob Napier45 Gotchas n BEGIN { use strict; } n There is no real function prototype mechanism (perl prototypes aren’t what you think) n << EOF u Watch out for spaces before the EOF n != vs ne, == vs eq, + vs. u number vs. string

3/18/99Llama to Ram -- Rob Napier46 Gotchas cont n &&, ||, and, or u && and || bind tightly. “and” and “or” bind loosely u Generally, you use && and || in boolean logic, while “and” and “or” are used for “or die” type error checking. n print vs u adds spaces. This includes inside a HERE- docs

3/18/99Llama to Ram -- Rob Napier47 Gotchas cont n `foo` or warn u This only warns if `foo` returns no output (even if that output is an error) n split (‘ ‘,...) u Splits on whitespace /[ \n\t]+/, not just ‘ ‘.

3/18/99Llama to Ram -- Rob Napier48 Wrapup n Thinking like a perl weenie means working with the language instead of against it. Even though “there’s more than one way to do it,” many of those ways fail to make good use of the power that perl offers. n The best way to learn to think in perl is to keep trying to make working scripts more perl-like. The best solution is usually the shortest solution that is still readable.