SlideShare a Scribd company logo
Program in Perl Style    Reference




             David Young
         yangboh@cn.ibm.com
              Feb. 2011
Program in Perl Style         Reference

Reference – the awesome reference
Program in Perl Style                                   Reference

What can we do with reference?
  Dispatch table
  Higher order functions




       In computer science, a dispatch table is a table of pointers to functions or
       methods. Use of such a table is a common technique when implementing
       late binding in object-oriented programming.
Program in Perl Style                      Reference

Dispatch table
# define your functions     # Push them   into hash table
                            %dispatch =   {
sub hellow {                   ”hellow”   => &hellow,
                               ”foo”      => $foo,
    print ”hellow world”;
                               “bar” =>   sub {
}                                           print ”bar foon”;
                                              },
                            }

$foo = sub {

    print ”foo world”;

}




                                          To be continued ...
Program in Perl Style                      Reference

Dispatch table - continued
  # dispatch tasks from your hash table
  $a = ”hellow”;
  &${dispatch->{$a}}();
  # hellow world
                                 # This is your hash table

  $rb = $dispatch->{”foo”};      %dispatch =   {
  &$rb();                           ”hellow”   => &hellow,
                                    ”foo”      => $foo,
  # foo world                       “bar” =>   sub {
                                                 print ”bar foon”;
                                                   },
  $rc = $dispatch->{”bar”};      }

  &$rc;
  # bar foo
Program in Perl Style                                  Reference

Reference – the awesome reference
  Dispatch table
  Higher order functions




   In mathematics and computer science, higher-order functions, functional forms, or
   functionals are functions which do at least one of the following:

     * take one or more functions as an input
     * output a function.
Program in Perl Style                        Reference

Higher Order Functions
sub category_defect {
    Local $_;           # just for a good habit
    my ( $column ) = @_;
    return sub {        # return a function instead a value
                my ( $condition, $line ) = @_;
                return $$line[ $column ] eq $condition ;
    }
}
Program in Perl Style                          Reference

Higher Order Functions
sub defect_by_category {
    local $_;
    my ($column, $col_value) = @_;
    my $category = &category_defect( $column ); # which return
    return sub {                                  # a function
                my (@result);
                my ($defect) = @_;
                return $defect       # invoke previous function
                      if &$category ($col_value, $defect) ;
    }
}
Program in Perl Style                       Reference

Higher Order Functions
sub defects_factory {
    local $_;
    my ($defect, @results);      # accept function as param
    my ($conditions, $defects ) = @_;
    foreach $defect ( @$defects ) {
    push @results, $defect if &$conditions ( $defect );
    }
    return @results;
}
Program in Perl Style                               Reference

Higher Order Functions
# $severity_1 holds a function reference, not a ordinary data

$severity_1 = &defect_by_category( SEVERITY, "1" );

$severity_2 = &defect_by_category( SEVERITY, "2" );

$severity_3 = &defect_by_category( SEVERITY, "3" );

$severity_4 = &defect_by_category( SEVERITY, "4" );



# transfer a function reference as parameter

@severity_1 = &defects_factory( $severity_1    , [ @defects ] );

@severity_2 = &defects_factory( $severity_2    , [ @defects ] );

@severity_3 = &defects_factory( $severity_3    , [ @defects ] );

@severity_4 = &defects_factory( $severity_4    , [ @defects ] );
Program in Perl Style Typeglobs

Typeglob is complex and dangures
Always be careful!!!
Program in Perl Style Typeglobs

Typeglobs and symble table
–– You'd better to read Camel book very carefully
 before start to using it.
 $spud   = "Wow!";

 @spud   = ("idaho", "russet");

 *potato = *spud;    # Alias potato to spud using typeglob assignment

 print "$potaton"; # prints "Wow!"

 print @potato, "n"; # prints "idaho russet"
Program in Perl Style Typeglobs

It is NOT the pointer you would expect in C
although they look similar literally
 $b = 10;

 {

     local *b;   # Save *b's values

     *b = *a;    # Alias b to a

     $b = 20;    # Same as modifying $a instead

 }               # *b restored at end of block

 print $a;       # prints "20"

 print $b;       # prints "10"
Program in Perl Style Typeglobs

Efficient parameter passing
  @array = (10,20);

  DoubleEachEntry(*array); # @array and @copy are identical.

  print "@array n"; # prints 20 40



  sub DoubleEachEntry {

      # $_[0] contains *array

      local *copy = shift;   # Create a local alias

      foreach $element (@copy) {

          $element *= 2;

      }

  }
Program in Perl Style Typeglobs

 Passing Filehandles to Subroutines
   Filehandle can not be passed to subroutines as scalars
   The only way to it is through typeglobs


   open (F, "/tmp/sesame") || die $!;
   read_and_print(*F);


   sub read_and_print {      # Filehandle G
       local (*G) = @_;      # is the same as filehandle F
       while (<G>) { print; }
   }
Program in Perl Style Typeglobs

Typeglobs are not always so explicitely
  cat test.pl
  #!/usr/bin/perl                          Be very careful!!!
  $foo = 123;
                                     Implicit typeglobs will make
  $bar = 321;
                                     your code very hard to
  $ra = "foo";
  print "$ra = $$ra n";                   understand
  while ($rb = <STDIN>) {
      chomp($rb);
      print "$rb = $$rb n";
  }                            bash-4.1$ echo "bar" | perl test2.pl
                               foo = 123
                               bar = 321
Program in Perl Style Typeglobs

But anyway ---- It's powerful!!!
Program in Perl Style Typeglobs

You can even build dispatch table from a plain file
cat a.cfg                    while ($a = <>) {

h say_hellow_to_a_friend         chomp($a);

                                 ($key, $func) = split ” ”, $a;
a accept_an_invitation
                                 $disptch{$key} = $func;
c confirm_an_invition
                             }
e send_email_to_a_friend
r refuse_an_invitation       sub command {

                             my ($cmd, arg) = @_;

Suppose you have functions   $rcmd = $disptch->{$cmd};

in above names               &$rcmd($arg) if defined &$rcmd;

                             }


                             &command("h", ”Tom”);
Program in Perl Style

Say good-bye to your endless ...
switch ...
case ...
if elsif ...
etc.
So think again why there is no 'switch',
  'case' ... in Perl?
Maybe you don't actually need it.

More Related Content

What's hot (20)

ODP
Introduction to Perl - Day 2
Dave Cross
 
PPT
LPW: Beginners Perl
Dave Cross
 
PDF
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Hipot Studio
 
PPT
Perl Presentation
Sopan Shewale
 
PPTX
Licão 13 functions
Acácio Oliveira
 
PPT
Class 3 - PHP Functions
Ahmed Swilam
 
PDF
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Workhorse Computing
 
PDF
Introduction to Perl and BioPerl
Bioinformatics and Computational Biosciences Branch
 
PPTX
Introduction in php
Bozhidar Boshnakov
 
PDF
PHP Unit 3 functions_in_php_2
Kumar
 
PDF
02 - Second meetup
EdiPHP
 
ODP
Advanced Perl Techniques
Dave Cross
 
PDF
Perl 5.10 for People Who Aren't Totally Insane
Ricardo Signes
 
PDF
Ruby 2.0
Uģis Ozols
 
PPT
php 2 Function creating, calling, PHP built-in function
tumetr1
 
PDF
Perl Scripting
Varadharajan Mukundan
 
PPT
Perl Basics with Examples
Nithin Kumar Singani
 
PDF
PHP 5.3 Overview
jsmith92
 
Introduction to Perl - Day 2
Dave Cross
 
LPW: Beginners Perl
Dave Cross
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Hipot Studio
 
Perl Presentation
Sopan Shewale
 
Licão 13 functions
Acácio Oliveira
 
Class 3 - PHP Functions
Ahmed Swilam
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Workhorse Computing
 
Introduction to Perl and BioPerl
Bioinformatics and Computational Biosciences Branch
 
Introduction in php
Bozhidar Boshnakov
 
PHP Unit 3 functions_in_php_2
Kumar
 
02 - Second meetup
EdiPHP
 
Advanced Perl Techniques
Dave Cross
 
Perl 5.10 for People Who Aren't Totally Insane
Ricardo Signes
 
Ruby 2.0
Uģis Ozols
 
php 2 Function creating, calling, PHP built-in function
tumetr1
 
Perl Scripting
Varadharajan Mukundan
 
Perl Basics with Examples
Nithin Kumar Singani
 
PHP 5.3 Overview
jsmith92
 

Similar to Programming in perl style (20)

PDF
What's New in Perl? v5.10 - v5.16
Ricardo Signes
 
PDF
Scripting3
Nao Dara
 
PDF
tutorial7
tutorialsruby
 
PDF
tutorial7
tutorialsruby
 
PDF
Marc’s (bio)perl course
Marc Logghe
 
PDF
newperl5
tutorialsruby
 
PDF
newperl5
tutorialsruby
 
KEY
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
PPT
Introduction to Perl
NBACriteria2SICET
 
PPT
Basic perl programming
Thang Nguyen
 
PDF
Practical approach to perl day1
Rakesh Mukundan
 
PDF
Lecture19-20
tutorialsruby
 
PDF
Lecture19-20
tutorialsruby
 
PDF
Unit VI
Bhavsingh Maloth
 
PPTX
Bioinformatica p4-io
Prof. Wim Van Criekinge
 
PPT
Perl Intro 2 First Program
Shaun Griffith
 
PDF
Perl intro
Swapnesh Singh
 
PPT
7.1.intro perl
Varun Chhangani
 
PDF
Lecture 22
rhshriva
 
PDF
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
What's New in Perl? v5.10 - v5.16
Ricardo Signes
 
Scripting3
Nao Dara
 
tutorial7
tutorialsruby
 
tutorial7
tutorialsruby
 
Marc’s (bio)perl course
Marc Logghe
 
newperl5
tutorialsruby
 
newperl5
tutorialsruby
 
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 
Introduction to Perl
NBACriteria2SICET
 
Basic perl programming
Thang Nguyen
 
Practical approach to perl day1
Rakesh Mukundan
 
Lecture19-20
tutorialsruby
 
Lecture19-20
tutorialsruby
 
Bioinformatica p4-io
Prof. Wim Van Criekinge
 
Perl Intro 2 First Program
Shaun Griffith
 
Perl intro
Swapnesh Singh
 
7.1.intro perl
Varun Chhangani
 
Lecture 22
rhshriva
 
Tutorial perl programming basic eng ver
Qrembiezs Intruder
 
Ad

Recently uploaded (20)

PDF
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
PPTX
How to Add New Item in CogMenu in Odoo 18
Celine George
 
PDF
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
PPTX
JSON, XML and Data Science introduction.pptx
Ramakrishna Reddy Bijjam
 
PDF
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
PPTX
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
PPTX
Martyrs of Ireland - who kept the faith of St. Patrick.pptx
Martin M Flynn
 
PPTX
Elo the HeroTHIS IS A STORY ABOUT A BOY WHO SAVED A LITTLE GOAT .pptx
JoyIPanos
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PDF
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
PPTX
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
DOCX
ANNOTATION on objective 10 on pmes 2022-2025
joviejanesegundo1
 
PDF
Rapid Mathematics Assessment Score sheet for all Grade levels
DessaCletSantos
 
DOCX
DLL english grade five goof for one week
FlordelynGonzales1
 
PPTX
2025 Completing the Pre-SET Plan Form.pptx
mansk2
 
PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PPTX
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
PPTX
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
 
PPTX
How to Manage Wins & Losses in Odoo 18 CRM
Celine George
 
PPTX
Photo chemistry Power Point Presentation
mprpgcwa2024
 
Lesson 1 : Science and the Art of Geography Ecosystem
marvinnbustamante1
 
How to Add New Item in CogMenu in Odoo 18
Celine George
 
Free eBook ~100 Common English Proverbs (ebook) pdf.pdf
OH TEIK BIN
 
JSON, XML and Data Science introduction.pptx
Ramakrishna Reddy Bijjam
 
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
Iván Bornacelly - Presentation of the report - Empowering the workforce in th...
EduSkills OECD
 
Martyrs of Ireland - who kept the faith of St. Patrick.pptx
Martin M Flynn
 
Elo the HeroTHIS IS A STORY ABOUT A BOY WHO SAVED A LITTLE GOAT .pptx
JoyIPanos
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
The Power of Compound Interest (Stanford Initiative for Financial Decision-Ma...
Stanford IFDM
 
How to Configure Taxes in Company Currency in Odoo 18 Accounting
Celine George
 
ANNOTATION on objective 10 on pmes 2022-2025
joviejanesegundo1
 
Rapid Mathematics Assessment Score sheet for all Grade levels
DessaCletSantos
 
DLL english grade five goof for one week
FlordelynGonzales1
 
2025 Completing the Pre-SET Plan Form.pptx
mansk2
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
How to Setup Automatic Reordering Rule in Odoo 18 Inventory
Celine George
 
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
 
How to Manage Wins & Losses in Odoo 18 CRM
Celine George
 
Photo chemistry Power Point Presentation
mprpgcwa2024
 
Ad

Programming in perl style

  • 1. Program in Perl Style Reference David Young [email protected] Feb. 2011
  • 2. Program in Perl Style Reference Reference – the awesome reference
  • 3. Program in Perl Style Reference What can we do with reference? Dispatch table Higher order functions In computer science, a dispatch table is a table of pointers to functions or methods. Use of such a table is a common technique when implementing late binding in object-oriented programming.
  • 4. Program in Perl Style Reference Dispatch table # define your functions # Push them into hash table %dispatch = { sub hellow { ”hellow” => &hellow, ”foo” => $foo, print ”hellow world”; “bar” => sub { } print ”bar foon”; }, } $foo = sub { print ”foo world”; } To be continued ...
  • 5. Program in Perl Style Reference Dispatch table - continued # dispatch tasks from your hash table $a = ”hellow”; &${dispatch->{$a}}(); # hellow world # This is your hash table $rb = $dispatch->{”foo”}; %dispatch = { &$rb(); ”hellow” => &hellow, ”foo” => $foo, # foo world “bar” => sub { print ”bar foon”; }, $rc = $dispatch->{”bar”}; } &$rc; # bar foo
  • 6. Program in Perl Style Reference Reference – the awesome reference Dispatch table Higher order functions In mathematics and computer science, higher-order functions, functional forms, or functionals are functions which do at least one of the following: * take one or more functions as an input * output a function.
  • 7. Program in Perl Style Reference Higher Order Functions sub category_defect { Local $_; # just for a good habit my ( $column ) = @_; return sub { # return a function instead a value my ( $condition, $line ) = @_; return $$line[ $column ] eq $condition ; } }
  • 8. Program in Perl Style Reference Higher Order Functions sub defect_by_category { local $_; my ($column, $col_value) = @_; my $category = &category_defect( $column ); # which return return sub { # a function my (@result); my ($defect) = @_; return $defect # invoke previous function if &$category ($col_value, $defect) ; } }
  • 9. Program in Perl Style Reference Higher Order Functions sub defects_factory { local $_; my ($defect, @results); # accept function as param my ($conditions, $defects ) = @_; foreach $defect ( @$defects ) { push @results, $defect if &$conditions ( $defect ); } return @results; }
  • 10. Program in Perl Style Reference Higher Order Functions # $severity_1 holds a function reference, not a ordinary data $severity_1 = &defect_by_category( SEVERITY, "1" ); $severity_2 = &defect_by_category( SEVERITY, "2" ); $severity_3 = &defect_by_category( SEVERITY, "3" ); $severity_4 = &defect_by_category( SEVERITY, "4" ); # transfer a function reference as parameter @severity_1 = &defects_factory( $severity_1 , [ @defects ] ); @severity_2 = &defects_factory( $severity_2 , [ @defects ] ); @severity_3 = &defects_factory( $severity_3 , [ @defects ] ); @severity_4 = &defects_factory( $severity_4 , [ @defects ] );
  • 11. Program in Perl Style Typeglobs Typeglob is complex and dangures Always be careful!!!
  • 12. Program in Perl Style Typeglobs Typeglobs and symble table –– You'd better to read Camel book very carefully before start to using it. $spud = "Wow!"; @spud = ("idaho", "russet"); *potato = *spud; # Alias potato to spud using typeglob assignment print "$potaton"; # prints "Wow!" print @potato, "n"; # prints "idaho russet"
  • 13. Program in Perl Style Typeglobs It is NOT the pointer you would expect in C although they look similar literally $b = 10; { local *b; # Save *b's values *b = *a; # Alias b to a $b = 20; # Same as modifying $a instead } # *b restored at end of block print $a; # prints "20" print $b; # prints "10"
  • 14. Program in Perl Style Typeglobs Efficient parameter passing @array = (10,20); DoubleEachEntry(*array); # @array and @copy are identical. print "@array n"; # prints 20 40 sub DoubleEachEntry { # $_[0] contains *array local *copy = shift; # Create a local alias foreach $element (@copy) { $element *= 2; } }
  • 15. Program in Perl Style Typeglobs Passing Filehandles to Subroutines Filehandle can not be passed to subroutines as scalars The only way to it is through typeglobs open (F, "/tmp/sesame") || die $!; read_and_print(*F); sub read_and_print { # Filehandle G local (*G) = @_; # is the same as filehandle F while (<G>) { print; } }
  • 16. Program in Perl Style Typeglobs Typeglobs are not always so explicitely cat test.pl #!/usr/bin/perl Be very careful!!! $foo = 123; Implicit typeglobs will make $bar = 321; your code very hard to $ra = "foo"; print "$ra = $$ra n"; understand while ($rb = <STDIN>) { chomp($rb); print "$rb = $$rb n"; } bash-4.1$ echo "bar" | perl test2.pl foo = 123 bar = 321
  • 17. Program in Perl Style Typeglobs But anyway ---- It's powerful!!!
  • 18. Program in Perl Style Typeglobs You can even build dispatch table from a plain file cat a.cfg while ($a = <>) { h say_hellow_to_a_friend chomp($a); ($key, $func) = split ” ”, $a; a accept_an_invitation $disptch{$key} = $func; c confirm_an_invition } e send_email_to_a_friend r refuse_an_invitation sub command { my ($cmd, arg) = @_; Suppose you have functions $rcmd = $disptch->{$cmd}; in above names &$rcmd($arg) if defined &$rcmd; } &command("h", ”Tom”);
  • 19. Program in Perl Style Say good-bye to your endless ... switch ... case ... if elsif ... etc. So think again why there is no 'switch', 'case' ... in Perl? Maybe you don't actually need it.