An Introduction to Perl

30
Per l March 2001 Hesham Wahby Mentor Graphics Egypt

description

March 2001 Hesham Wahby Mentor Graphics Egypt. An Introduction to Perl. Presentation Outline. Introduction Hello world Basic Perl language Regular expressions Some common Perl functions A glimpse of some advanced features Conclusion. Introduction: What is Perl?. - PowerPoint PPT Presentation

Transcript of An Introduction to Perl

Page 1: An Introduction to Perl

An Introduction to

PerlMarch 2001

Hesham WahbyMentor Graphics Egypt

Page 2: An Introduction to Perl

Presentation Outline

➢ Introduction

➢ Hello world

➢ Basic Perl language

➢ Regular expressions

➢ Some common Perl functions

➢ A glimpse of some advanced features

➢ Conclusion

Page 3: An Introduction to Perl

Introduction:

What is Perl?➢ Practical Extraction and Report Language.

➢ Created in 1987 by Larry Wall, now maintained by hundreds of people.

➢ A high-level programming/scripting language, combining features from C, Sed, Awk, Unix shells and many others.

➢ Originally designed for text (and binary) string processing.

➢ "Perl is designed to make the easy jobs easy and the hard jobs possible."

➢ Perl motto: "There's more than one way to do it."

➢ "Pathologically Eclectic Rubbish Lister"?

Page 4: An Introduction to Perl

Introduction:

Features of Perl➢ Language features:

➢ Simple to start using. Very rich set of tools.

➢ Basically function oriented, with OO extensions.

➢ C-style program structure. Free-style command syntax.

➢ Weakly-typed variables. Implicit declaration. Sophisticated data structures.

➢ Built-in regular expressions.

➢ Built-in database access.

➢ POSIX compliant.

➢ Extensible using modules.

Page 5: An Introduction to Perl

Introduction:

Features of Perl

➢ Compiler features:➢ Compiled at load-time.

➢ Can be translated to optimized C code.

➢ Can also be directly integrated with other C/C++ code by either calling it or getting called by it.

➢ Built-in debugger.

Page 6: An Introduction to Perl

Introduction:

Getting Perl

➢ Perl is GPL: freely distributable, open-source.

➢ Where to get Perl:➢ The Perl Homepage:

http://www.perl.com/➢ CPAN (Comprehensive Perl Archive Network):

http://www.cpan.org/➢ ActivePerl Homepage (for Win32):

http://www.activestate.com/ActivePerl/

Page 7: An Introduction to Perl

Hello world!➢ Example Perl program: "hello.pl":

#!/usr/mgc/bin/perlprint "Hello world!"

➢ Command line:> perl hello.plHello world!>

➢ To run as executable:> chmod +x hello.pl> ./hello.pl

Page 8: An Introduction to Perl

Hello world:

Command-line options> perl [options] program.pl program_arguments

> perl -e '$x=7; print 23*$x; print "\n"'

> preprocess test.pl | perl

> perl -h

> perl -v

> perl -w program.pl

> perl -d program.pl

> perl -c program.pl

> perl -Ipath_for_modules program.pl

> perl -Mmodule_name program.pl

Page 9: An Introduction to Perl

#!/usr/mgc/bin/perl

%types = (int => 'Integers', float => 'Reals');

open INFILE, $ARGV[0];@lines = <INFILE>;close INFILE;

# Search for variablesforeach (@lines) {

if (/^\s*(int|float)\s*(\w*)/) {push @list[$1], $2;}

}

$" = ', '; # Print them outforeach $type (keys %list) {

print "$types[$type]: @list[$type].\n"}

Hello world:A more extensive example

Page 10: An Introduction to Perl

Basic Perl language:

Data types

➢ Scalars

$var➢ Lists (Arrays)

@var $var[n]➢ Hashes (Associative arrays)

%var $var[???]➢ Complex data structures

Page 11: An Introduction to Perl

Basic Perl language:

Special variables➢ Default argument: $_➢ Input record separator: $/➢ Output field separator: $,➢ List separator: $"➢ Process Id: $$➢ Program name: $0➢ Command-line arguments: @ARGV➢ Subroutine arguments: @_➢ Environment variables: %ENV

Page 12: An Introduction to Perl

Basic Perl language:

Context$a = 'Take'; $x = 2; $y = '007';@list = ('red','green','blue');

print $a . ' ' . $x;$b = "Take $x\n";$z = $x + $y; $c = "$x + $y";

print "@list", @list, $#list;$i = @list; print $i;print $list[2];print $list;$listLen = ("purple", @list, 'yellow', @list+2);

$, = "\n"; print %ENV;print (keys %ENV); print (values %ENV);

Page 13: An Introduction to Perl

Basic Perl Language:

Control constructs

if (expression) {block}

if (expression) {block} else {block}

if (expression) {block}elsif (expression) {block}elsif (expression) {block}...else {block}

unless (expression) {block}

unless (expression) {block} else {block}

Page 14: An Introduction to Perl

Basic Perl Language:

Control constructs

while (expression) {block}

while (expression) {block} continue {block}

do {block} while (expression);

until (expression) {block}

for (statement; expression; statement) {block}

foreach variable (list) {block}

label:goto label;

Page 15: An Introduction to Perl

Basic Perl language:

File-handling➢ Opening a file:

open FILE, $file #inputopen FILE, "<$file"; #inputopen (FILE, ">$file"); #outputopen FILE, ">>$file"; #append

➢ Closing a file:close FILE;

➢ Reading from a file:$line = <FILE>; @lines = <FILE>;read FILE, $data, 78, 10;

➢ Writing to a file:print FILE "String.\n";

➢ Binary files:binmode FILE;

➢ Reading output of a command-line:$output = `ls -l $dir`

Page 16: An Introduction to Perl

Basic Perl language:

Subroutines

sub Add {

local ($x, $sum);$sum = 0;foreach $x (@_) {

$sum += $x;}

$sum;}

$test = &Add (2, $number, @listofnumbers);

Page 17: An Introduction to Perl

Regular expressions:

Pattern matching$str = "The large swirls are eddies in the Gulf.";$str =~ m/die/ ; #true$str =~ /gulf/ ; #false$str !~ /gulf/i ; #false$_ = $str;/^the/ ; #false

➢ Modifiers:g: match globallyi: case-insensitive matchingm: multi-lineo: compile onces: single-linex: extended RE

Page 18: An Introduction to Perl

Regular expressions:

Basic elements

\ Quote next metacharacter. Any character^ Start of line$ End of line\b \B (Non-)Word boundary

\w \W (Non-)Word character\s \S (Non-)Whitespace\d \D (Non-)Digit

\t Tab\n Newline

$var Match contents of variable${var} To explicitly delimit variables

Page 19: An Introduction to Perl

Regular expressions:

Basic elements

| Alternation() Grouping[] Character class[^] Negative character class

* Match 0 or more+ Match 1 or more? Match 1 or 0{n} Match exectly n{n,} Match n or more{n,m} Match n or more, but less than m

*? +? ?? {}? Reverse 'greedy' behaviour

Page 20: An Introduction to Perl

Regular expressions:

Extracting matched patterns

if ($match = ($string =~ /\d+/)) {print $match }

($a, $b) = /(\w)\s(\w)/;

@mygroups = (`groups` =~ /\b(\w+)\b/g);

/setenv\s*(\w+)\s*(\w+)/;$vars{

nmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm /mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm /$1} = $2;

Page 21: An Introduction to Perl

Regular expressions:

Substitution and translation➢ Substitution:

$str =~ s/green/blue/g;

s/\b(.)(.*)(.)\b/\3\2\1/g;

s/(\d+)/1 + $1/eg;

➢ Translation:

tr/abc/ABC/;

tr/A-Z/QWERTYUIOPASDFGHJKLZXCVBNM/;

Page 22: An Introduction to Perl

Regular expressions:

Some example REs

/\/\s*0*\.0*/ ;/[a-z]['")]*[.!?]+['")]*\s/ ;

s|/usr/bin|/usr/local/bin| ;$count = s/Mister\b/Mr./g ;s/\d+/$&*2/eg ;s/(\$\w+)/$1/eeg ;

$program =~ s {/\* # Match opening delimiter..*? # Match minimal characters.\*/ # Match closing delimiter.

} []gsx;

Page 23: An Introduction to Perl

Some common Perl functions:

Strings➢ length

$l = length $string;$l = length; #uses $_

➢ split@list = split /[,\s]/, $string, 10;($name, $value) = split /=/;

➢ substr$piece = substr $string, 2, 10;

➢ chop & chomp$c = chop $string;chomp @lines;$/ = ' '; chomp;

➢ pack & unpack

Page 24: An Introduction to Perl

Some common Perl functions:

Lists➢ push & pop

push @list, $item;$num = push @list, @items;$item = pop @list;

➢ shift & unshift$item = shift @list;unshift @list, $item;

➢ sort@sorted = sort @list;print sort {$a <=> $b} @list;

➢ splice@sublist = splice @list, 2, 5;splice @list, $off, $len, @newitems;

Page 25: An Introduction to Perl

Some common Perl functions:

Miscellaneous

➢ time & localtime($sec,$min,$hour,$mday,$mon,$year, $wday,$yday,$isdst) = localtime time;$now = localtime;# "Thu Oct 13 04:54:34 1994"

➢ rand & srandsrand time;$x = rand 10;

Page 26: An Introduction to Perl

A glimpse of someadvanced features

➢ References and complex data structures

➢ Formats

➢ POD: plain old documentation

➢ Modules

➢ Perl/Tk and Perl/CGI

➢ Databases

➢ OO Perl

Page 27: An Introduction to Perl

Conclusion:

When to use Perl

➢ Advanced "shell scripts".

➢ Process management.

➢ Writing quick routines to batch process files or access databases.

➢ Anything involving a lot of string handling (ASCII or binary).

➢ CGI and other web-programming.

Page 28: An Introduction to Perl

Conclusion:

When not to use Perl

➢ Heavy computations.

➢ Large applications.

Page 29: An Introduction to Perl

Conclusion:

Further resources

➢ Books:

➢ "Programming Perl" 2/e, Larry Wall, Tom Christiansen & Randal Schwartz. (The camel book.)

➢ "Learning Perl" 2/e, Randal Schwartz, Tom Christiansen & Larry Wall. (The llama book.)

➢ "Perl in a Nutshell", Ellen Siever, Stephen Spainhour & Nathan Patwardhan.

➢ "Advanced Perl Programming", Sriram Srinivasan.

Page 30: An Introduction to Perl

Conclusion:

Further resources

➢ Web-sites:

➢ Perl Core Documentation:

http://www.perldoc.com/

➢ Nik Silver's Perl Tutorial:

http://www.comp.leeds.ac.uk/nik/start.html