SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Downloaden Sie, um offline zu lesen
Perl Programming
                 Course
                  Subroutines




Krassimir Berov

I-can.eu
Contents
1. What is a Subroutine
2. Defining Subroutines
3. Invoking Subroutines
4. Subroutine arguments
5. Retrieving data from calling subroutines
   Operator caller
6. Return values. Operator wantarray
7. Scope and Declarations
What is a Subroutine
• Subroutine
  • a user-defined function
  • identifier for a code block
    • letters, digits, and underscores
    • can't start with a digit
    • optional ampersand (&) in front
Defining a Subroutine
• sub NAME BLOCK
  sub NAME (PROTO) BLOCK
  sub NAME : ATTRS BLOCK
  sub NAME (PROTO) : ATTRS BLOCK
  • Without a BLOCK it's just a forward declaration
  • Without a NAME, it's an anonymous function
    declaration – return value: CODE ref
    See: perlfaq7/What's a closure?

  • May optionally have attribute lists
    See: attributes, Attribute::Handlers
  • A subroutine may be defined anywhere in your
    program
Defining a Subroutine
• sub NAME (PROTO) BLOCK
  • The function declaration must be visible at
    compile time
  • The prototype is in effect only when not using
    the & character
  • Method calls are not influenced by prototypes
    either
  • The intent is primarily to let you define
    subroutines that work like built-in functions
  • See:perlsub/Prototypes
Invoking Subroutines
• Example:sub.pl
  sub hope;
  sub syntax($) {
      print "This is 'Subroutines' slide "
          .($_[0]||1) ."n";
  }
  syntax $ARGV[0];
  #syntax();#Not enough arguments for...
  hope;
  hope();
  &hope;
  nope();
  #nope;#Bareword "nope" not allowed...
  sub hope { print "I hope you like Perl!n"; }
  sub nope { print "I am a dangerous Bareword.n" }
  my $code_ref = sub { print 'I am a closure'.$/ };
  print $code_ref,$/;#CODE(0x817094c)
  $code_ref->() or &$code_ref;
Subroutine arguments
• @_
  contains the parameters passed to the
  subroutine
• if you call a function with two arguments, they
  will be stored in $_[0] and $_[1]
• Avoid to use ($_[0] .. $_[n]) directly unless you
  want to modify the arguments.
• The array @_ is a local array, but its elements
  are aliases for the actual scalar parameters
Subroutine arguments
• Example: sub_args.pl
  use strict; use warnings; $ = $/;
  sub modify($) {
      print "The alias holding "
          .($_[0]++) ." will be modifyedn";
  }

  modify($ARGV[0]);
  print $ARGV[0];

  copy_arg($ARGV[0]);
  print $ARGV[0];

  sub copy_arg {
      my ($copy) = @_;
      print "The copy holding "
          .($copy++) ." will NOT modify $ARGV[0]n";
  }
Retrieving data from
              calling subroutines
• caller EXPR
  caller
 Returns the context of the current subroutine call.
  • In scalar context, returns the caller's package name if
    there is a caller and the undefined value otherwise.
  • In list context, returns
    ($package, $filename, $line) = caller;
  • In list context with EXPR, returns more...
  • The value of EXPR indicates how many call frames to
    go back before the current one.
Retrieving data from
              calling subroutines
• Example:caller.pl
  use Data::Dumper;
  sub dump_stacktrace {
      print shift || 'Dumping stacktrace:';
      my $call_frame = 1;
      local $,=$/;
      my %i;
      while(($i{package}, $i{filename}, $i{line},
             $i{subroutine}, $i{hasargs}, $i{wantarray},
             $i{evaltext}, $i{is_require}, $i{hints},
             $i{bitmask}, $i{hinthash})
             = caller($call_frame++)){
          print Data::Dumper->Dump(
              [%i],['call '.($call_frame-1)]
          );
      }
  }
Retrieving data from
              calling subroutines                    (2)
• Example: caller2.pl
  package Calling;
  require 'caller.pl';
  run(@ARGV);
  sub run {
      print '"run" called';
      OtherPackage::second(shift);
  }

  sub OtherPackage::second {
      print '"second" called';
      my@a = ThirdPackage::third(@_);
  }

  sub ThirdPackage::third {
      print '"third" called';
      dump_stacktrace('This is the stack trace:');
  }
Return values.
            Operator wantarray
• Return values
  • (list, scalar, or void) depending on the
    context of the subroutine call
  • If you specify no return value:
    • returns an empty list in list context,
    • the undefined value in scalar context,
    • nothing in void context.
  • If you return one or more lists:
    • these will be flattened together
Return values.
            Operator wantarray                 (2)
• Return values
  • A return statement may be used to
    specify a return value
  • The last evaluated statement becomes
    automatically the return value
  • If the last statement is a foreach or a
    while, the returned value is unspecified
  • The empty sub returns the empty list
Return values.
              Operator wantarray
• Return values: return.pl
  #prints favorite pet or a list of all pets
  my @pets = qw|Goldy Amelia Jako|;

  print run($ARGV[0]);
  sub run {
      my $pref = shift||'';#favorite or list of pets
      if($pref) { favorite() }
      else       { local $,=$/; print pets() }
  }
  sub favorite {
      'favorite:'.$pets[1]
  }
  sub pets {
      return ('all pets:', @pets)
  }
Return values.
            Operator wantarray
• wantarray
  • Returns true if the context of the currently
    executing subroutine or eval is looking for
    a list value
  • Returns false if the context is looking for a
    scalar.
  • Returns the undefined value if the context
    is looking for no value (void context).
Return values.
                Operator wantarray
• wantarray
  # prints favorite pet or a list of all pets,
  # or nothing depending on context
  my @pets = qw|Goldy Amelia Jako|;
  run();

  sub run {
      if(defined $ARGV[0]) {
          if($ARGV[0]==1)    { my $favorite = pets() }
          elsif($ARGV[0]==2) { my @pets = pets()     }
      }
      else { pets() }
  }

  sub pets {
      local $,=$/ and print ('all pets:', @pets) if wantarray;
      return if not defined wantarray;
      print 'favorite:'.$pets[1] if not wantarray;
  }
Scope and Declarations
• Variable scoping, private variables.
• Scope declarations: my, local, our
Scope
• What is scope?
  • Lexical/static scope can be defined by
    • the boundary of a file
    • any block – {}
    • a subroutine
    • an eval
    • using my
  • Global/package/dynamic scope can be defined
    by using sub, our and local declarations
    respectively
Declarations
• my - declare and assign a local variable
  (lexical scoping)
• our - declare and assign a package
  variable (lexical scoping)
• local - create a temporary value for a
  global variable (dynamic scoping)
Declarations
• my $var;
  A my declares the listed variables to be local
  (lexically) to the enclosing block, file, or eval.
• If more than one value is listed, the list must be
  placed in parentheses.
• a virable declared via my is private
• See: perlfunc/my, perlsub/Private Variables via my()
  my $dog;           #declare $dog lexically local
  my (@cats, %dogs); #declare list of variables local
  my $fish = "bob"; #declare $fish lexical, and init it
  my @things = ('fish','cat');
  #declare @things lexical, and init it
Declarations
• my $var;
  Example:
 my $dog = 'Puffy';
 {
     my $dog = 'Betty';
     print 'My dog is named ' . $dog;
 }
 print 'My dog is named ' . $dog;
 my ($fish, $cat, $parrot) = qw|Goldy Amelia Jako|;
 print $fish, $cat, $parrot;
 #print $lizard;
 #Global symbol "$lizard" requires explicit package
 name...
Declarations
• our EXPR
  • associates a simple name with a package
    variable in the current package
  • can be used within the current scope
    without prefixing it with package name
  • can be used outside the current package
    by prefixing it with the package name
Declarations
• our – Example:
  {
      package GoodDogs;
      print 'We are in package ' . __PACKAGE__;
      our $dog = 'Puffy';
      {
          print 'Our dog is named ' . $dog;
          my $dog = 'Betty';
          print 'My dog is named ' . $dog;
      }
      print 'My dog is named ' . $dog;
  }{#delete this line and experiment
      package BadDogs;
      print $/.'We are in package ' . __PACKAGE__;
      #print 'Previous dog is named ' . $dog;
      print 'Your dog is named ' . $GoodDogs::dog;
      our $dog = 'Bobby';
      print 'Our dog is named ' . $dog;
  }
Declarations
• local EXPR
  • modifies the listed variables to be local to the
    enclosing block, file, or eval
  • If more than one value is listed, the list must
    be placed in parentheses
Declarations
• local EXPR                                             (2)

 WARNING:
  • prefer my instead of local – it's faster and safer
  • exceptions are:
     • global punctuation variables
     • global filehandles and formats
     • direct manipulation of the Perl symbol table itself
  • local is mostly used when the current value of a
    variable must be visible to called subroutines
Declarations
• local – Example:
  use English;
  {
      local $^O = 'Win32';
      local $OUTPUT_RECORD_SEPARATOR = "n-----n";#$
      local $OUTPUT_FIELD_SEPARATOR = ': ';#$,
      print 'We run on', $OSNAME;

      open my $fh, $PROGRAM_NAME or die $OS_ERROR;#$0 $!
      local $INPUT_RECORD_SEPARATOR ; #$/ enable
  localized slurp mode
      my $content = <$fh>;
      close $fh;
      print $content;
      #my $^O = 'Solaris';#Can't use global $^O in
  "my"...
  }
  print 'We run on ', $OSNAME;
Subroutines




Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Kamal Acharya
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applicationsAhsan Mansiv
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)MD Sulaiman
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Jumping statements
Jumping statementsJumping statements
Jumping statementsSuneel Dogra
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQLrehaniltifat
 

Was ist angesagt? (20)

Java program structure
Java program structureJava program structure
Java program structure
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Oops
OopsOops
Oops
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)Dynamic Memory Allocation(DMA)
Dynamic Memory Allocation(DMA)
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
Stack and its applications
Stack and its applicationsStack and its applications
Stack and its applications
 
Data structures using c
Data structures using cData structures using c
Data structures using c
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)Fundamentals of OOP (Object Oriented Programming)
Fundamentals of OOP (Object Oriented Programming)
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Jumping statements
Jumping statementsJumping statements
Jumping statements
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 

Ähnlich wie Subroutines

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
 
Scripting3
Scripting3Scripting3
Scripting3Nao Dara
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationWorkhorse Computing
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl courseMarc Logghe
 
Programming in perl style
Programming in perl styleProgramming in perl style
Programming in perl styleBo Hua Yang
 
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
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perlworr1244
 
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
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3Nate Abele
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1Rakesh Mukundan
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 

Ähnlich wie Subroutines (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)
 
Scripting3
Scripting3Scripting3
Scripting3
 
Syntax
SyntaxSyntax
Syntax
 
BSDM with BASH: Command Interpolation
BSDM with BASH: Command InterpolationBSDM with BASH: Command Interpolation
BSDM with BASH: Command Interpolation
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl course
 
Programming in perl style
Programming in perl styleProgramming in perl style
Programming in perl style
 
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
 
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
 
Dades i operadors
Dades i operadorsDades i operadors
Dades i operadors
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
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
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Practical PHP 5.3
Practical PHP 5.3Practical PHP 5.3
Practical PHP 5.3
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1
 
PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 

Mehr von Krasimir Berov (Красимир Беров) (14)

Хешове
ХешовеХешове
Хешове
 
Списъци и масиви
Списъци и масивиСписъци и масиви
Списъци и масиви
 
Скаларни типове данни
Скаларни типове данниСкаларни типове данни
Скаларни типове данни
 
Въведение в Perl
Въведение в PerlВъведение в Perl
Въведение в Perl
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Network programming
Network programmingNetwork programming
Network programming
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Hashes
HashesHashes
Hashes
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Kürzlich hochgeladen

Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

Subroutines

  • 1. Perl Programming Course Subroutines Krassimir Berov I-can.eu
  • 2. Contents 1. What is a Subroutine 2. Defining Subroutines 3. Invoking Subroutines 4. Subroutine arguments 5. Retrieving data from calling subroutines Operator caller 6. Return values. Operator wantarray 7. Scope and Declarations
  • 3. What is a Subroutine • Subroutine • a user-defined function • identifier for a code block • letters, digits, and underscores • can't start with a digit • optional ampersand (&) in front
  • 4. Defining a Subroutine • sub NAME BLOCK sub NAME (PROTO) BLOCK sub NAME : ATTRS BLOCK sub NAME (PROTO) : ATTRS BLOCK • Without a BLOCK it's just a forward declaration • Without a NAME, it's an anonymous function declaration – return value: CODE ref See: perlfaq7/What's a closure? • May optionally have attribute lists See: attributes, Attribute::Handlers • A subroutine may be defined anywhere in your program
  • 5. Defining a Subroutine • sub NAME (PROTO) BLOCK • The function declaration must be visible at compile time • The prototype is in effect only when not using the & character • Method calls are not influenced by prototypes either • The intent is primarily to let you define subroutines that work like built-in functions • See:perlsub/Prototypes
  • 6. Invoking Subroutines • Example:sub.pl sub hope; sub syntax($) { print "This is 'Subroutines' slide " .($_[0]||1) ."n"; } syntax $ARGV[0]; #syntax();#Not enough arguments for... hope; hope(); &hope; nope(); #nope;#Bareword "nope" not allowed... sub hope { print "I hope you like Perl!n"; } sub nope { print "I am a dangerous Bareword.n" } my $code_ref = sub { print 'I am a closure'.$/ }; print $code_ref,$/;#CODE(0x817094c) $code_ref->() or &$code_ref;
  • 7. Subroutine arguments • @_ contains the parameters passed to the subroutine • if you call a function with two arguments, they will be stored in $_[0] and $_[1] • Avoid to use ($_[0] .. $_[n]) directly unless you want to modify the arguments. • The array @_ is a local array, but its elements are aliases for the actual scalar parameters
  • 8. Subroutine arguments • Example: sub_args.pl use strict; use warnings; $ = $/; sub modify($) { print "The alias holding " .($_[0]++) ." will be modifyedn"; } modify($ARGV[0]); print $ARGV[0]; copy_arg($ARGV[0]); print $ARGV[0]; sub copy_arg { my ($copy) = @_; print "The copy holding " .($copy++) ." will NOT modify $ARGV[0]n"; }
  • 9. Retrieving data from calling subroutines • caller EXPR caller Returns the context of the current subroutine call. • In scalar context, returns the caller's package name if there is a caller and the undefined value otherwise. • In list context, returns ($package, $filename, $line) = caller; • In list context with EXPR, returns more... • The value of EXPR indicates how many call frames to go back before the current one.
  • 10. Retrieving data from calling subroutines • Example:caller.pl use Data::Dumper; sub dump_stacktrace { print shift || 'Dumping stacktrace:'; my $call_frame = 1; local $,=$/; my %i; while(($i{package}, $i{filename}, $i{line}, $i{subroutine}, $i{hasargs}, $i{wantarray}, $i{evaltext}, $i{is_require}, $i{hints}, $i{bitmask}, $i{hinthash}) = caller($call_frame++)){ print Data::Dumper->Dump( [%i],['call '.($call_frame-1)] ); } }
  • 11. Retrieving data from calling subroutines (2) • Example: caller2.pl package Calling; require 'caller.pl'; run(@ARGV); sub run { print '"run" called'; OtherPackage::second(shift); } sub OtherPackage::second { print '"second" called'; my@a = ThirdPackage::third(@_); } sub ThirdPackage::third { print '"third" called'; dump_stacktrace('This is the stack trace:'); }
  • 12. Return values. Operator wantarray • Return values • (list, scalar, or void) depending on the context of the subroutine call • If you specify no return value: • returns an empty list in list context, • the undefined value in scalar context, • nothing in void context. • If you return one or more lists: • these will be flattened together
  • 13. Return values. Operator wantarray (2) • Return values • A return statement may be used to specify a return value • The last evaluated statement becomes automatically the return value • If the last statement is a foreach or a while, the returned value is unspecified • The empty sub returns the empty list
  • 14. Return values. Operator wantarray • Return values: return.pl #prints favorite pet or a list of all pets my @pets = qw|Goldy Amelia Jako|; print run($ARGV[0]); sub run { my $pref = shift||'';#favorite or list of pets if($pref) { favorite() } else { local $,=$/; print pets() } } sub favorite { 'favorite:'.$pets[1] } sub pets { return ('all pets:', @pets) }
  • 15. Return values. Operator wantarray • wantarray • Returns true if the context of the currently executing subroutine or eval is looking for a list value • Returns false if the context is looking for a scalar. • Returns the undefined value if the context is looking for no value (void context).
  • 16. Return values. Operator wantarray • wantarray # prints favorite pet or a list of all pets, # or nothing depending on context my @pets = qw|Goldy Amelia Jako|; run(); sub run { if(defined $ARGV[0]) { if($ARGV[0]==1) { my $favorite = pets() } elsif($ARGV[0]==2) { my @pets = pets() } } else { pets() } } sub pets { local $,=$/ and print ('all pets:', @pets) if wantarray; return if not defined wantarray; print 'favorite:'.$pets[1] if not wantarray; }
  • 17. Scope and Declarations • Variable scoping, private variables. • Scope declarations: my, local, our
  • 18. Scope • What is scope? • Lexical/static scope can be defined by • the boundary of a file • any block – {} • a subroutine • an eval • using my • Global/package/dynamic scope can be defined by using sub, our and local declarations respectively
  • 19. Declarations • my - declare and assign a local variable (lexical scoping) • our - declare and assign a package variable (lexical scoping) • local - create a temporary value for a global variable (dynamic scoping)
  • 20. Declarations • my $var; A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval. • If more than one value is listed, the list must be placed in parentheses. • a virable declared via my is private • See: perlfunc/my, perlsub/Private Variables via my() my $dog; #declare $dog lexically local my (@cats, %dogs); #declare list of variables local my $fish = "bob"; #declare $fish lexical, and init it my @things = ('fish','cat'); #declare @things lexical, and init it
  • 21. Declarations • my $var; Example: my $dog = 'Puffy'; { my $dog = 'Betty'; print 'My dog is named ' . $dog; } print 'My dog is named ' . $dog; my ($fish, $cat, $parrot) = qw|Goldy Amelia Jako|; print $fish, $cat, $parrot; #print $lizard; #Global symbol "$lizard" requires explicit package name...
  • 22. Declarations • our EXPR • associates a simple name with a package variable in the current package • can be used within the current scope without prefixing it with package name • can be used outside the current package by prefixing it with the package name
  • 23. Declarations • our – Example: { package GoodDogs; print 'We are in package ' . __PACKAGE__; our $dog = 'Puffy'; { print 'Our dog is named ' . $dog; my $dog = 'Betty'; print 'My dog is named ' . $dog; } print 'My dog is named ' . $dog; }{#delete this line and experiment package BadDogs; print $/.'We are in package ' . __PACKAGE__; #print 'Previous dog is named ' . $dog; print 'Your dog is named ' . $GoodDogs::dog; our $dog = 'Bobby'; print 'Our dog is named ' . $dog; }
  • 24. Declarations • local EXPR • modifies the listed variables to be local to the enclosing block, file, or eval • If more than one value is listed, the list must be placed in parentheses
  • 25. Declarations • local EXPR (2) WARNING: • prefer my instead of local – it's faster and safer • exceptions are: • global punctuation variables • global filehandles and formats • direct manipulation of the Perl symbol table itself • local is mostly used when the current value of a variable must be visible to called subroutines
  • 26. Declarations • local – Example: use English; { local $^O = 'Win32'; local $OUTPUT_RECORD_SEPARATOR = "n-----n";#$ local $OUTPUT_FIELD_SEPARATOR = ': ';#$, print 'We run on', $OSNAME; open my $fh, $PROGRAM_NAME or die $OS_ERROR;#$0 $! local $INPUT_RECORD_SEPARATOR ; #$/ enable localized slurp mode my $content = <$fh>; close $fh; print $content; #my $^O = 'Solaris';#Can't use global $^O in "my"... } print 'We run on ', $OSNAME;