An Introduction to Perl by ewghwehws

VIEWS: 3 PAGES: 30

									An Introduction to




Perl
             March 2001
           Hesham Wahby
         Mentor Graphics Egypt
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?
➢   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."
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.
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.
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/
Hello world!
➢   Example Perl program: "hello.pl":
       #!/usr/mgc/bin/perl
       print "Hello world!
       "


➢   Command line:
       > perl hello.pl
       Hello world!
       >


➢   To run as executable:
       > chmod +x hello.pl
       > ./hello.pl
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
Hello world:
 A more extensive example
 #!/usr/mgc/bin/perl

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

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

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

 $" = ', '; # Print them out
 foreach $type (keys %list) {
     print "$types[$type]: @list[$type].\n"
     }
Basic Perl language:
 Data types
➢   Scalars
     $var
➢   Lists (Arrays)
    @var     $var[n]
➢   Hashes (Associative arrays)
     %var    $var[???]
➢   Complex data structures
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
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);
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}
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;
Basic Perl language:
 File-handling
➢   Opening a file:
     open   FILE, $file #input
     open   FILE, "<$file"; #input
     open   (FILE, ">$file"); #output
     open   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`
Basic Perl language:
 Subroutines
sub Add {
   local ($x, $sum);
   $sum = 0;
   foreach $x (@_) {
       $sum += $x;
       }
   $sum;
   }


$test = &Add (2, $number, @listofnumbers);
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 globally
    i:   case-insensitive matching
    m:   multi-line
    o:   compile once
    s:   single-line
    x:   extended RE
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
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
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{
     nmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
     mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
     mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
     mmmmmmmmmmmmmmmmmmmmmmmmmmmmm
     /mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
     mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
     mmmmmmm         /$1} = $2;
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/;
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;
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
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;
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 & srand
    srand time;
    $x = rand 10;
A glimpse of some
 advanced features
➢   References and complex data structures
➢   Formats
➢   POD: plain old documentation
➢   Modules
➢   Perl/Tk and Perl/CGI
➢   Databases
➢   OO 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.
Conclusion:
 When not to use Perl


➢   Heavy computations.
➢   Large applications.
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.
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

								
To top