Docstoc

Perl

Document Sample
Perl Powered By Docstoc
					Farshad Khoshkhui
    Omid Sefat
Happy Birthday Perl!
   Perl is Sweet Sixteen!
   20 December 1987 Larry Wall Released Perl 1.
   Current Version Of Perl is 5.8
   Perl 6 will be Released in 2004 and will be a
    complete rewrite of Perl.
                 Http://history.perl.org
Perl is …
   Acronym for Practical Extraction and Report
    Language
   Open Source & Free high-level Programming
    Language.
   Scripting language which is both relatively
    simple to learn and yet remarkably powerful.
   Popular and widely used, especially for
    system administration and WWW
    programming.
Perl is …
   Available on all computing platforms.
            Unix/Linux, Windows, Macintosh, Palm OS

   Designed to understand and manipulate text.
   Fast , Simple to Learn and Extensible.
   Object Oriented.
   Weak typed
         More Perl is … on http://www.perl.org
Variable Types
   Scalars:
       A scalar represents a single value:
           my $animal = "camel";
           my $answer = 42;
   Scalar values can be strings, integers or floating point numbers, and
    Perl will automatically convert
   Scalar values can be Between them as required. There is no need
    to pre-declare your variable types.
Variable Types
    Arrays
         An array represents a list of values:

           my @animals = ("camel", "llama", "owl");
           my @numbers = (23, 42, 69);
           my @mixed = ("camel", 42, 1.23);

    Arrays are zero-indexed. Here's how you get at elements in an array:

           print $animals[0];            # prints "camel"
           print $animals[1];            # prints "llama"
    You can do various useful things to lists:

          my @sorted = sort @animals;
          my @backwards = reverse @numbers;
Variable Types
 Hash
A hash represents a set of key/value pairs:
        my %fruit_color = ("apple", "red", "banana", "yellow");

You can use whitespace and the "=>" operator to lay them out more
  nicely:
 my %fruit_color = (
            apple => "red",
            banana => "yellow",
         );

 To get at hash elements:
         $fruit_color{"apple"};               # gives "red"
  You can get at lists of keys and values with "keys()" and "values()".
       my @fruits = keys %fruit_colors
       my @colors = values %fruit_colors;
Perl Syntax
. Perl statements end in a semi-colon:
      print "Hello, world";
. Comments start with a hash symbol and run to the end of the line:
      # This is a comment
. However, only double quotes "interpolate" variables and
   special characters such as newlines ("\n"):
     print "Hello, $name\n";               # works fine
     print 'Hello, $name\n';              # prints $name\n
   literally
Conditional & Looping
Conrtructs
   If (EXPR) BLOCK
         if (EXPR) BLOCK else BLOCK
         if (EXPR) BLOCK elsif (EXPR) BLOCK
        else BLOCK
   While (EXPR) BLOCK
   While (EXPR) BLOCK continue BLOCK
   For (EXPR; EXPR; EXPR) BLOCK
   Foreach VAR (LIST) BLOCK
   Foreach VAR (LIST) BLOCK continue BLOCK
Conditional & Looping
Conrtructs
  Example:
 foreach (@array) {
             print "This element is $_\n";
           }
 # you don't have to use the default $_ either...
  foreach my $key (keys %hash) {
     print "The value of $key is $hash{$key}\n";
           }
 Continue in C loops  Next in Perl.
 Break in C loops  Last in Perl.
Conditional & Looping
Conrtructs
   for ($i = 1; $i < 10; $i++) {
           ...
        }

   is the same as this:

        $i = 1;
        while ($i < 10) {
           ...
        } continue {
           $i++;
        }
Subroutines
     Sub max{
      my ($num1,$num2)=@_;
      if ($num1>=$num2) {return $num1}
      else {return $num2}
}
print max(5,10); #prints 10

    sub substring {
    my($str, $from, $to) = @_;

    sub substring($, $, $) { #with prototype
    my($str, $from, $to) = @_;

  sub max {
       my $max = shift(@_);
       foreach $foo (@_) {
          $max = $foo if $max < $foo;}
       return $max;
     }
$bestday = max($mon,$tue,$wed,$thu,$fri);
Parameter Passing
   Making Refrences

    $scalarref = \$foo;
    $arrayref = \@ARGV
    $hashref = \%ENV;
    $coderef = \&handler;

   Using Refrences
    $bar = $$scalarref;
    $$arrayref[0] = "January";
    $$hashref{"KEY"} = "VALUE";
    &$coderef(1,2,3);
Parameter Passing
sub changeFirstArg{
    $_[0]=9; #think of @_ members as original variables
}

sub changeFirstArg2{
    my $first_arg=$_[0]; #let’s make a copy of it
    $first_arg=9;}

sub changeFirstArg3{
    my $array_ref=$_[0];
    $$array_ref[0]=9;}

@array=(1,2,3);
changeFirstArg(@array); #@_ would be (1,2,3) not ((1,2,3))
print $array[0]."\n"; #prints 9
@array=(1,2,3);
changeFirstArg2(@array);
print $array[0]."\n"; #prints 1
@array=(1,2,3);
changeFirstArg3(\@array); #@_ would be (refrence to @array), useful for passing multiple references
print $array[0]."\n"; #prints 9
Scopes
   Global (ex. $a=“foo”;)
   Local or Block Private (ex. My $a=“foo”;)
   Dynamic or Pakage global (ex. Local $a=“foo”;)

my $a = "foo";
     if ($some_condition) {
         my $b = "bar";
         print $a;      # prints "foo"
         print $b;      # prints "bar"
     }
     print $a;          # prints "foo"
     print $b;          # prints nothing; $b has fallen out of scope
String Manipulation
 Concatanation $str=“Hello ” . “World”.”!”;
 print <<EOF;

           The price is $Price.
EOF
 Perl Regular Expressions



   Samples:
$output=`w`;
@output_splited=split /\\n/,$output;
$output_splited[0]=~/^ [0-9]{2}:[0-9]{2}:[0-9]{2} up[\s]+([0-9]{1,2}:
                       [0-9]{2}),[\s]+([0-9]+) users,[\s]+load average: ([0-9\.]+),
                       ([0-9\.]+), ([0-9\.]+).*/;
print "Server is up for --$1-- and --$2-- users are logged in"."\n";
print "Load Average for past 1,5 and 15 minutes are --$3-- --$4-- --$5--"."\n";

print "\n"."The w output was:"."\n";
print $output."\n";

Output:
Server is up for --3:53-- and --3-- users are logged in
Load Average for past 1,5 and 15 minutes are --0.13-- --0.24-- --0.24--

The w output was:
 19:04:04 up 3:53, 3 users, load average: 0.13, 0.24, 0.2
USER TTY          LOGIN@ IDLE JCPU PCPU WHAT
farshad vc/1    15:11 3:52m 0.00s 0.00s /bin/sh /usr/X11R6/bin/startx
omid pts/12 16:50 3:02 0.24s 0.05s nano -w a2
farshad pts/14 18:47 0.00s 0.03s 0.01s sshd: farshad [priv]
More RE Examples
   perl -i.bak -p -e
    's/xyz\.rice\.edu/abc.rice.edu/ig' *.html

   perl -i.bak -p \ -e
    's#file://localhost/localpath/#http://riceinfo.rice
    .edu/remotepath/#ig' \ *.html
Threads
   use threads;
    $thr = threads->new(\&sub1);
    $thr->join();

sub sub1 {
    print "In the thread\n";
 }
Object Oriented
   sub Cow::speak {
       print "a Cow goes moooo!\n";
    }
    sub Horse::speak {
       print "a Horse goes neigh!\n";
     }
     sub Sheep::speak {
       print "a Sheep goes baaaah!\n"
     }

Cow::speak;
Horse::speak;
Sheep::speak;

   This results in:

    a Cow goes moooo!
    a Horse goes neigh!
    a Sheep goes baaaah!
Object Oriented
{ package Animal;
        sub speak {
          my $class = shift;
          print "a $class goes ", $class->sound, "!\n"
        }
}
 { package Cow;
        @ISA = qw(Animal);
        sub sound { "moooo" }
 }
 bless $talking, Cow;
Exceptions/Error handling
 No Exception in perl,sorry!
 Or statements

Open(FH,”<list.txt”) or die “Can’t open file: $!”;

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:20
posted:8/19/2012
language:
pages:22