SlideShare uma empresa Scribd logo
1 de 19
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.

Mais conteúdo relacionado

Mais procurados

Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2Dave Cross
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners PerlDave Cross
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’PhinneyAnonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’PhinneyHipot Studio
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP FunctionsAhmed Swilam
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Workhorse Computing
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2Kumar
 
02 - Second meetup
02 - Second meetup02 - Second meetup
02 - Second meetupEdiPHP
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsaneRicardo Signes
 
php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in functiontumetr1
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overviewjsmith92
 

Mais procurados (20)

Introduction to Perl - Day 2
Introduction to Perl - Day 2Introduction to Perl - Day 2
Introduction to Perl - Day 2
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’PhinneyAnonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Php
PhpPhp
Php
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 
Perl
PerlPerl
Perl
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
 
Introduction to Perl and BioPerl
Introduction to Perl and BioPerlIntroduction to Perl and BioPerl
Introduction to Perl and BioPerl
 
Introduction in php
Introduction in phpIntroduction in php
Introduction in php
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
 
02 - Second meetup
02 - Second meetup02 - Second meetup
02 - Second meetup
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Perl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally InsanePerl 5.10 for People Who Aren't Totally Insane
Perl 5.10 for People Who Aren't Totally Insane
 
Ruby 2.0
Ruby 2.0Ruby 2.0
Ruby 2.0
 
php 2 Function creating, calling, PHP built-in function
php 2 Function creating, calling,PHP built-in functionphp 2 Function creating, calling,PHP built-in function
php 2 Function creating, calling, PHP built-in function
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
PHP 5.3 Overview
PHP 5.3 OverviewPHP 5.3 Overview
PHP 5.3 Overview
 

Semelhante a Perl Style Reference - Dispatch Tables, Higher Order Functions & Typeglobs

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationWorkhorse Computing
 
What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16Ricardo Signes
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongersbrian d foy
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsRoy Zimmer
 
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng verQrembiezs Intruder
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning PerlDave Cross
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In PerlKang-min Liu
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to PerlDave Cross
 
Whatsnew in-perl
Whatsnew in-perlWhatsnew in-perl
Whatsnew in-perldaoswald
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perlworr1244
 

Semelhante a Perl Style Reference - Dispatch Tables, Higher Order Functions & Typeglobs (20)

Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command Interpolation
 
What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
You Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager NeedsYou Can Do It! Start Using Perl to Handle Your Voyager Needs
You Can Do It! Start Using Perl to Handle Your Voyager Needs
 
Cleancode
CleancodeCleancode
Cleancode
 
Tutorial perl programming basic eng ver
Tutorial perl programming basic eng verTutorial perl programming basic eng ver
Tutorial perl programming basic eng ver
 
Beginning Perl
Beginning PerlBeginning Perl
Beginning Perl
 
First steps in PERL
First steps in PERLFirst steps in PERL
First steps in PERL
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Perl bhargav
Perl bhargavPerl bhargav
Perl bhargav
 
Whatsnew in-perl
Whatsnew in-perlWhatsnew in-perl
Whatsnew in-perl
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 

Último

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Último (20)

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Perl Style Reference - Dispatch Tables, Higher Order Functions & Typeglobs

  • 1. Program in Perl Style Reference David Young yangboh@cn.ibm.com 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.