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




Krassimir Berov

I-can.eu
Contents
1. Declarations
2. Simple Statements
3. Compound Statements
4. Comments and POD
5. Conditional Statements
   (Statement Modifiers)
6. Loops and loop control
7. Logical operators
8. Mathematical operators
9. Operator Precedence and Associativity
10.Error handling
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)
• sub - declare a subroutine, possibly
  anonymously
Declarations
• Example:
  use strict; use warnings;
  our $dog = 'Puffy';
  {
      local $ =$/;
      print 'A line-feed is appended.';
  }
  tell_dogs();
  print 'No new line at the end. ';
  print 'A line feed is appended.'.$/; #;)

  sub tell_dogs {
      local $ =$/;
      print 'Our dog is named ' . $dog;
      my $dog = 'Betty';
      print 'My dog is named ' . $dog;
  }
Simple Statements
• The only kind of simple statement is an
  expression evaluated for its side effects.
• Every simple statement must be terminated
  with a semicolon(;).
• If it is the final statement in a block, the
  semicolon is optional.
• eval{} and do{} look like compound
  statements, but aren't
• eval{} and do{} need an explicit termination
Simple Statements
• Example:
 use strict;
 use warnings;
 $ = $/;
 my $simple = 'A simple statement.';
 print $simple;
 eval { print $simple };
 do { print $simple };
 do {
      $_++;
      print $simple ,' ',$_,'+2'
 };
Compound Statements

• A compound statement usually contains:
  • labels
  • conditional constructions and blocks
  • several simple statements enclosed in
    a block
  • the block defines a scope
Compound Statements
                                                      (2)
• A BLOCK is delimited by curly brackets – {}
• The braces are required
• Perl offers several ways to write conditionals
  without curly brackets.
• The continue BLOCK is always executed just
  before the conditional is about to be evaluated
  again.
• A LABEL gives its associated control flow
  structure a name.
  if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
  LABEL while (EXPR) BLOCK
  LABEL until (EXPR) BLOCK continue BLOCK
  LABEL for (EXPR; EXPR; EXPR) BLOCK
  LABEL foreach VAR (LIST) BLOCK continue BLOCK
Compound Statements
• Examples:
use strict; use warnings; $ = $/;
use strict; use warnings; $ = $/;

unless( open(FH,$0)){
    die 'I do not exist on disk!'. $^E
}
else {
    local $ = undef;#slurp mode
    my $c=1;
    print "$0: ", sprintf('%02d',$c++), " $_" while <FH>;
}
print $/.'---';
my $hashref = {me=>1,you=>2,he=>3};
exists $hashref->{she}
    and print 'she: '.$hashref->{she}
        or print 'she does not exists.'
            and print sort values %$hashref;
Compound Statements
                                                   (2)
• Examples:
  my $c = 0;
  while ($c <= 10){
      print $c;
  }
  continue {
      $c++;
      print $c;
  };
  ########################################
  A_LABEL: for my $m (1..10){
      ANOTHER: for my $s(0..60) {
          last A_LABEL if $m > 4;
          last if $s > 4 and print '---';
          print sprintf('%1$02d.%2$02d',$m,$s) ;
      }
  }
Comments and POD
• Text from a "#" character until the end of the line is a
  comment
  Exceptions include "#" inside a string or regular expression.
• POD is a simple-to-use markup language used for writing
  documentation for Perl, Perl programs, and Perl modules.
   use strict; use warnings; $ = $/;
   my $simple = 'A simple statement.#not a comment.';
   print $simple;#this is a comment
   $simple =~ s#a##ig;
   print $simple;
   $simple =~ s/#//ig;
   print $simple;
   =pod
   I like to use POD for multi-line comments
   but it is much more than that.
   =cut
   print $0 . ' finished.';
Conditional Statements
• Truth and Falsehood
• if/elsif/unless/else
• Statement modifiers (suffix notation)
Conditional Statements
• Truth and Falsehood
  • The number 0, the strings '0' and '', the
    empty list (), and undef are all false in a
    boolean context
  • All other values are true
  • Negation of a true value by ! or not returns a
    special false value.
    When evaluated as a string it is treated as '',
    but as a number, it is treated as 0.
Conditional Statements
• if/elsif/unless/else
  use strict; use warnings; $ = $/;
  unless( open(FH,$0) ){
      die 'I do not exist on disk!'. $^E
  }
  else {
      local $ = undef; my $c = 1;
      print "$0: ", sprintf('%02d',$c++), " $_"
            while <FH>;
  }
  my $hashref = {me=>1,you=>2,he=>3};
  if ( exists $hashref->{she} ) {
      print 'she:'.$hashref->{she};
  }
  else {
      print 'she does not exists.';
      print sort values %$hashref;
  }
Conditional Statements
• Statement modifiers (suffix notation)
  use strict; use warnings; $ = $/;
  {
       my $c=1;
       local $ = undef;
       do {
               print "$0: ", sprintf('%02d',$c++), " $_"
               while <FH>
           } if open(FH,$0)
               or die 'I do not exist on disk!'. $^E;
  }
  my $hashref = {me=>1,you=>2,he=>3};
  print 'she:'.$hashref->{she}
       if ( exists $hashref->{she} );
  do {
       print 'she does not exists.';
       print sort values %$hashref;
  } unless exists $hashref->{she};
Loops and Loop Control
• Loops
  • for
  • foreach
  • while
  • until
  • do while/until
Loops and Loop Control
• for
  • Perl's C-style for loop works like the
    corresponding while loop
  for ($i = 1; $i < 10; $i++) {
      ...
  }

    is (almost) the same as
  $i = 1;
  while ($i < 10) {
      ...
  } continue {
      $i++;
  }
Loops and Loop Control
• foreach
  • Iterates over a normal list value and sets the variable
    VAR to be each element of the list in turn
  • If preceded with my, it is visible only within the loop
  • Otherwise, the variable is implicitly local to the loop
    and regains its former value upon exiting the loop
  • If VAR is omitted, $_ is set to each value
  • You can use foreach for readability or for for
    brevity
Loops and Loop Control
• foreach – Example:
  my @pets = qw|Goldy Amelia Jako|;
  my $favorite = 'Puffy';;
  foreach $favorite(@pets) {
       print 'My favourite pet is:' . $favorite;
  }
  print 'My favourite pet is:' . $favorite;#Puffy
  for $favorite(@pets) {
       print 'My favourite pet is:' . $favorite;
  }
  print 'My favourite pet is:' . $favorite;#Puffy
  unshift @pets,$favorite;
  for (@pets) {
       print 'My favourite pet is:' . $_;
  }
  #...
Loops and Loop Control
• while
 repeats a block of code as long as a condition is
 true
• do while
 executes the do at least once before evaluating
 condition in while
  $|++;# enable $OUTPUT_AUTOFLUSH
  my @sufx = qw(th st nd rd th th th th th th th);
  my $i = 1;
  while ($i<=10) {
      print "This is $i$sufx[$i] iteration";
      sleep 1;
      $i++;
  }
  do { print "The $i became $i" } while $i < 10;
  print '- ' x $c, $c and $c++ while ($c<=10);
Loops and Loop Control
• until
 repeats a block of code as long as a condition
 is NOT true
• do until
 executes the do at least once before evaluating
 condition in until
  $|++;# enable $OUTPUT_AUTOFLUSH
  my @sufx = qw(th st nd rd th th th th th th th);
  $i = 10;
  until ($i<1) {
      print "This is $i$sufx[$i] countdown";
      sleep 1;
      $i--;
  }
  do {print "T$i became $i"; $i--} until $i < 1;
Loops and Loop Control
• Loop control
  • next
  • last
  • redo
  • continue
Loops and Loop Control
• Loop control
  • next
    starts the next iteration of the loop
    (continue in C)
  • last
    immediately exits the loop (break in C)
  • redo
    restarts the loop block without evaluating
    the conditional again
  • continue
    is always executed just before
    the conditional is about to be evaluated again
Loops and Loop Control
• Loop control
  • next
    • If LABEL is omitted, refers to the innermost
      enclosing loop
    • cannot be used to exit a block which
      returns a value such as
      eval {}, sub {} or do {}
    • should not be used to exit
      a grep() or map() operation
Loops and Loop Control
                                                     (2)
• Loop control
  • next
  my $c = 1;
  while (<DATA>){
      next unless /perl/;
      chomp and print "$c: $_";
      $c++;
  }
  __DATA__
  This section of a perl file
  can be used by the perl program
  above in the same file to store
  and use some textual data
  perl rocks!!!
  Will the above line print if we remove this one?
Loops and Loop Control
• Loop control
  • last
    • If LABEL is omitted, refers to the innermost
      enclosing loop
    • cannot be used to exit a block which
      returns a value such as
      eval {}, sub {} or do {}
    • should not be used to exit a grep() or map()
      operation
Loops and Loop Control
                                       (2)
• Loop control
  • last
  my $c = 1;
  while (<DATA>){
      last unless /perl/;
      chomp and print "$c: $_";
      $c++;
  }
  __DATA__
  This section of a perl file
  can be used by the perl program
  above in the same file to store
  and use some textual data
  perl rocks!!!
Loops and Loop Control
• Loop control
  • redo
    • skips the remaining BLOCK
    • does not execute any continue block
      (even if it exists)
    • If the LABEL is omitted, the command refers
      to the innermost enclosing loop
    • cannot be used to retry a block which returns
      a value such as eval {}, sub {} or do {}
    • should not be used to exit a grep() or map()
      operation
Loops and Loop Control
                                                     (2)
• Loop control
           my ($c, $redone) = (1,0);
  • redo   while (<DATA>){
               chomp; print "$c: $_"; $c++;
               if ($_ =~ /perl/ and not $redone) {
                    $redone++;
                    redo;
               }
               elsif($_ =~ /perl/ and $redone) {
                    $redone--;
                    next;
               }
           }
           __DATA__
           This section of a perl file
           can be used by the perl program
           above in the same file to store
           and use some textual data
           perl rocks!!!
Loops and Loop Control
• Loop control
  • continue
    • can be used to increment a loop variable,
      even when the loop has been continued via
      the next statement
    • last, next, or redo may appear within a
      continue block
    • last, next(!), and redo will behave
     as in the main block
Loops and Loop Control
• Loop control
  • continue

  my ($c,$reached_10) = (1,);
  while ($c) {
      print '- ' x $c, $c;
  } continue {
      last if ($c == 1 and $reached_10);
      $c-- if $reached_10;
      $c++ if $c < 10 and not $reached_10;
      $reached_10++ if $c == 10;
  }
Logical Operators
• &&/and
  • Binary "and" returns the logical conjunction of
    the two surrounding expressions.
  • and is equivalent to && except for the very low
    precedence
  • the right expression is evaluated only if the left
    expression is true
  my ($me,$you) = qw(me you);
  print 'We are here:'.($me && $you) if ($me && $you);
  print 'We are here:'.($me and $you) if ($me and $you);
  undef $me;
  print 'We are here:' if ($me and $you)
     or die 'Someone';
Logical Operators
• ||/or
  • Binary or returns the logical disjunction
    of the two surrounding expressions
  • or is equivalent to || except for the very
    low precedence
  • the right expression is evaluated only if
    the left expression is false
  • use or only for control flow
Logical Operators
• ||/or
  Example:
  my ($me,$you) = qw(me you);
  print 'Somebody is here:'.($me || $you)
     if ($me || $you);
  print 'Somebody is here:'.($me or $you)
     if ($me or $you);

  ($me,$you) = ('me', undef);
  print 'Somebody is here:'.($me or $you)
      if ($me or $you) or die 'Nooo..';

  ($me,$you) = (undef, 'you');
  print 'Somebody is here:'.($me or $you)
      if ($me or $you) or die 'no one';
Logical Operators
• !/not
• Unary "not" returns the logical negation
  of the expression to its right
• the equivalent of "!" except for the very
  low precedence

  use Config;
  print 'Do my perl uses old threads?';
  print 'No' if !$Config{use5005threads};
  print 'I do not have extras' if !$Config{extras};
  print 'I do not have mail' if not $Config{mail};
Logical Operators
• The Ternary Operator, ?:
  • ?: is an if-then-else test, all in one
    expression
  • "ternary" – takes three operands
  • if the first expression is true, the second is
    evaluated, the third is ignored
  • if the first expression is false, the second is
    ignored, and the third is evaluated as the
    value of the whole
   1 < 2 ? print 'true' : print 'false';
Mathematical Operators
• Additive Operators
  • Binary "+" returns the sum of two
    numbers
  • Binary "-" returns the difference of two
    numbers
  • Note: Binary "." concatenates two strings
  print   3+2;
  print   2-3;
  print   2.3; #;)
  print   '2'.'3';
Mathematical Operators
• Multiplicative Operators
  • Binary "*" multiplies two numbers
  • Binary "/" divides two numbers
  • Binary "%" computes the modulus of two
    numbers
  • Binary "x" is the repetition operator
  print   3 * 2;
  print   2 / 3;
  print   "oddn" if 3 % 2; #;)
  print   2 x 3;
Mathematical Operators
• Exponentiation
  • Binary "**" is the exponentiation operator
  • binds more tightly than unary minus, so
    -2**4 is -(2**4), not (-2)**4
• Auto-increment and Auto-decrement
  • "++" and "--" work as in C
  print   -2**4;#-16
  my $a   = 2;
  print   $a++; #2
  print   ++$a; #4
  print   $a--; #4
  print   --$a; #2
Operator Precedence
               and Associativity
• Operator precedence means some operators are
  evaluated before others.
• Operator associativity defines what happens if a
  sequence of the same operators is used one after
  another: whether the evaluator will evaluate the left
  operations first or the right.
• See perlop/Operator Precedence and Associativity
   #precedence
   2 + 4 * 5 == 2 + 20 == 22   and not 6 * 5 == 30

   #associativity
   8 - 4 – 2 == 4 - 2 == 2   and not 8 - 2 == 6
Operator Precedence
                  and Associativity
• listed from highest precedence to lowest
• operators borrowed from C keep the same precedence
  relationship with each other
       left          terms and list operators (leftward)
       left          ->
       nonassoc      ++ --
       right         **
       right         ! ~  and unary + and -
       left          =~ !~
       left          * / % x
       left          + - .
       left          << >>
       nonassoc      named unary operators
       nonassoc      < > <= >= lt gt le ge
       nonassoc      == != <=> eq ne cmp ~~
   ...
   to be continued
Operator Precedence
                  and Associativity
                                                  (2)
• Many operators can be overloaded for objects.
• See the overload manpage
   ...
   continued
       left        &
       left        | ^
       left        &&
       left        || //
       nonassoc    .. ...
       right       ?:
       right       = += -= *= etc.
       left        , =>
       nonassoc    list operators (rightward)
       right       not
       left        and
       left        or xor
Error Handling
• die
• warn
• eval{statements()};
  do{something()} if($@)
  warn 'Default variable is undefined' unless $_;

  eval ' a syntax error or any failure';

  if($@){
     warn 'You spoiled everything';
  }
Error Handling
• Carp
  • carp - warn of errors
    (from perspective of caller)
  • cluck - warn of errors with stack backtrace
    (not exported by default)
  • croak - die of errors
    (from perspective of caller)
  • confess - die of errors with stack backtrace
Error Handling
• Carp – Example:
  use Carp qw(cluck croak confess);
  other_place();

  croak "We're outta here!";

  sub here {
      $ARGV[0] ||= 'try';
      if ($ARGV[0] =~ /try/){
          cluck "nThis is how we got here!"
      }
      elsif ($ARGV[0] =~ /die/){
          confess "nNothing to live for!";
      }
  }
  sub there { here; }
  sub other_place { there }
Syntax




Questions?
Exercises
1. Write a program that iterates from 3 to 15 and then
   from 15 to 3. Print every iteration on the screen.
   Try to write it from scratch.
2. Write a program that dies with an error message if
   the argument on the command line contains the
   word “die”.
3. Write a program that tries to guess the argument
   to the script if it contains the numbers 1 or 2 and
   prints different messages depending on the
   argument. Try not to use if/elsif/unless/else.

Weitere ähnliche Inhalte

Was ist angesagt?

Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisaujihisa
 
Lecture 22
Lecture 22Lecture 22
Lecture 22rhshriva
 
Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Andrew Shitov
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Nikita Popov
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In PerlKang-min Liu
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Developmentjsmith92
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev AssistantDave Cross
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1Dave Cross
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - phpHung-yu Lin
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021Ayesh Karunaratne
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Lin Yo-An
 
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
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHPWim Godden
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6 brian d foy
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHPAhmed Swilam
 
perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbaivibrantuser
 

Was ist angesagt? (20)

Hacking Parse.y with ujihisa
Hacking Parse.y with ujihisaHacking Parse.y with ujihisa
Hacking Parse.y with ujihisa
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6Text in search queries with examples in Perl 6
Text in search queries with examples in Perl 6
 
Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)Static Optimization of PHP bytecode (PHPSC 2017)
Static Optimization of PHP bytecode (PHPSC 2017)
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Improving Dev Assistant
Improving Dev AssistantImproving Dev Assistant
Improving Dev Assistant
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021PHP Enums - PHPCon Japan 2021
PHP Enums - PHPCon Japan 2021
 
PerlScripting
PerlScriptingPerlScripting
PerlScripting
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
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
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
perl course-in-mumbai
 perl course-in-mumbai perl course-in-mumbai
perl course-in-mumbai
 

Andere mochten auch

Tissue culture and virus indexing for the production of clean planting materials
Tissue culture and virus indexing for the production of clean planting materialsTissue culture and virus indexing for the production of clean planting materials
Tissue culture and virus indexing for the production of clean planting materialsILRI
 
Demonstration speech rubric
Demonstration speech rubricDemonstration speech rubric
Demonstration speech rubricnallely88aguilar
 
Chapter12 - Designing System Interfaces, Controls and Security(Demo Presentat...
Chapter12 - Designing System Interfaces, Controls and Security(Demo Presentat...Chapter12 - Designing System Interfaces, Controls and Security(Demo Presentat...
Chapter12 - Designing System Interfaces, Controls and Security(Demo Presentat...John Ely Masculino
 
Characteristics of outcomes based assessment
Characteristics of outcomes based assessmentCharacteristics of outcomes based assessment
Characteristics of outcomes based assessmentWilliam Kapambwe
 
Delayed recovery from anaesthesia by prof. minnu m. panditrao
Delayed recovery from anaesthesia by prof. minnu m. panditraoDelayed recovery from anaesthesia by prof. minnu m. panditrao
Delayed recovery from anaesthesia by prof. minnu m. panditraoMinnu Panditrao
 
Computer Vision, Deep Learning, OpenCV
Computer Vision, Deep Learning, OpenCVComputer Vision, Deep Learning, OpenCV
Computer Vision, Deep Learning, OpenCVFarshid Pirahansiah
 
Qualitative Data Analysis (Strategies)
Qualitative Data Analysis (Strategies)Qualitative Data Analysis (Strategies)
Qualitative Data Analysis (Strategies)guest7f1ad678
 
Data Mining: Application and trends in data mining
Data Mining: Application and trends in data miningData Mining: Application and trends in data mining
Data Mining: Application and trends in data miningDataminingTools Inc
 
Of Studies by: Francis Bacon
Of Studies by: Francis BaconOf Studies by: Francis Bacon
Of Studies by: Francis BaconCaroline Lace
 
Organizational behaviour (Stress Management)
Organizational behaviour (Stress Management)Organizational behaviour (Stress Management)
Organizational behaviour (Stress Management)Lila Bear
 
Strategic Management: Organizational Design
Strategic Management: Organizational DesignStrategic Management: Organizational Design
Strategic Management: Organizational DesignTriune Global
 
6 Thinking Hats
6 Thinking Hats6 Thinking Hats
6 Thinking Hatsnathanr07
 
HOSPITALITY FOOD & BEVERAGE SERVICE
HOSPITALITY FOOD & BEVERAGE SERVICE HOSPITALITY FOOD & BEVERAGE SERVICE
HOSPITALITY FOOD & BEVERAGE SERVICE Brahmas Pandey
 
Functional theories
Functional theoriesFunctional theories
Functional theoriesLy Berns
 
Metadata in data warehouse
Metadata in data warehouseMetadata in data warehouse
Metadata in data warehouseSiddique Ibrahim
 

Andere mochten auch (20)

Tissue culture and virus indexing for the production of clean planting materials
Tissue culture and virus indexing for the production of clean planting materialsTissue culture and virus indexing for the production of clean planting materials
Tissue culture and virus indexing for the production of clean planting materials
 
Demonstration speech rubric
Demonstration speech rubricDemonstration speech rubric
Demonstration speech rubric
 
Chapter12 - Designing System Interfaces, Controls and Security(Demo Presentat...
Chapter12 - Designing System Interfaces, Controls and Security(Demo Presentat...Chapter12 - Designing System Interfaces, Controls and Security(Demo Presentat...
Chapter12 - Designing System Interfaces, Controls and Security(Demo Presentat...
 
The importance of effective management
The importance of effective managementThe importance of effective management
The importance of effective management
 
Gibberellins
Gibberellins Gibberellins
Gibberellins
 
Sustainable housing
Sustainable housingSustainable housing
Sustainable housing
 
Characteristics of outcomes based assessment
Characteristics of outcomes based assessmentCharacteristics of outcomes based assessment
Characteristics of outcomes based assessment
 
Delayed recovery from anaesthesia by prof. minnu m. panditrao
Delayed recovery from anaesthesia by prof. minnu m. panditraoDelayed recovery from anaesthesia by prof. minnu m. panditrao
Delayed recovery from anaesthesia by prof. minnu m. panditrao
 
Computer Vision, Deep Learning, OpenCV
Computer Vision, Deep Learning, OpenCVComputer Vision, Deep Learning, OpenCV
Computer Vision, Deep Learning, OpenCV
 
Qualitative Data Analysis (Strategies)
Qualitative Data Analysis (Strategies)Qualitative Data Analysis (Strategies)
Qualitative Data Analysis (Strategies)
 
Data Mining: Application and trends in data mining
Data Mining: Application and trends in data miningData Mining: Application and trends in data mining
Data Mining: Application and trends in data mining
 
Of Studies by: Francis Bacon
Of Studies by: Francis BaconOf Studies by: Francis Bacon
Of Studies by: Francis Bacon
 
Psychological test
Psychological testPsychological test
Psychological test
 
Organizational behaviour (Stress Management)
Organizational behaviour (Stress Management)Organizational behaviour (Stress Management)
Organizational behaviour (Stress Management)
 
Strategic Management: Organizational Design
Strategic Management: Organizational DesignStrategic Management: Organizational Design
Strategic Management: Organizational Design
 
Data Mining: Outlier analysis
Data Mining: Outlier analysisData Mining: Outlier analysis
Data Mining: Outlier analysis
 
6 Thinking Hats
6 Thinking Hats6 Thinking Hats
6 Thinking Hats
 
HOSPITALITY FOOD & BEVERAGE SERVICE
HOSPITALITY FOOD & BEVERAGE SERVICE HOSPITALITY FOOD & BEVERAGE SERVICE
HOSPITALITY FOOD & BEVERAGE SERVICE
 
Functional theories
Functional theoriesFunctional theories
Functional theories
 
Metadata in data warehouse
Metadata in data warehouseMetadata in data warehouse
Metadata in data warehouse
 

Ähnlich wie Syntax

Ähnlich wie Syntax (20)

Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Learn perl in amc square learning
Learn perl in amc square learningLearn perl in amc square learning
Learn perl in amc square learning
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
Scripting ppt
Scripting pptScripting ppt
Scripting ppt
 
Scripting3
Scripting3Scripting3
Scripting3
 
Perl one liners
Perl one linersPerl one liners
Perl one liners
 
Licão 12 decision loops - statement iteration
Licão 12 decision loops - statement iterationLicão 12 decision loops - statement iteration
Licão 12 decision loops - statement iteration
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Linux shell script-1
Linux shell script-1Linux shell script-1
Linux shell script-1
 
Perl basics for Pentesters
Perl basics for PentestersPerl basics for Pentesters
Perl basics for Pentesters
 
Barely Legal Xxx Perl Presentation
Barely Legal Xxx Perl PresentationBarely Legal Xxx Perl Presentation
Barely Legal Xxx Perl Presentation
 
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
 
OS.pdf
OS.pdfOS.pdf
OS.pdf
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 

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

Хешове
ХешовеХешове
Хешове
 
Списъци и масиви
Списъци и масивиСписъци и масиви
Списъци и масиви
 
Скаларни типове данни
Скаларни типове данниСкаларни типове данни
Скаларни типове данни
 
Въведение в 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
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Hashes
HashesHashes
Hashes
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Kürzlich hochgeladen

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Kürzlich hochgeladen (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Syntax

  • 1. Perl Programming Course Syntax Krassimir Berov I-can.eu
  • 2. Contents 1. Declarations 2. Simple Statements 3. Compound Statements 4. Comments and POD 5. Conditional Statements (Statement Modifiers) 6. Loops and loop control 7. Logical operators 8. Mathematical operators 9. Operator Precedence and Associativity 10.Error handling
  • 3. 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) • sub - declare a subroutine, possibly anonymously
  • 4. Declarations • Example: use strict; use warnings; our $dog = 'Puffy'; { local $ =$/; print 'A line-feed is appended.'; } tell_dogs(); print 'No new line at the end. '; print 'A line feed is appended.'.$/; #;) sub tell_dogs { local $ =$/; print 'Our dog is named ' . $dog; my $dog = 'Betty'; print 'My dog is named ' . $dog; }
  • 5. Simple Statements • The only kind of simple statement is an expression evaluated for its side effects. • Every simple statement must be terminated with a semicolon(;). • If it is the final statement in a block, the semicolon is optional. • eval{} and do{} look like compound statements, but aren't • eval{} and do{} need an explicit termination
  • 6. Simple Statements • Example: use strict; use warnings; $ = $/; my $simple = 'A simple statement.'; print $simple; eval { print $simple }; do { print $simple }; do { $_++; print $simple ,' ',$_,'+2' };
  • 7. Compound Statements • A compound statement usually contains: • labels • conditional constructions and blocks • several simple statements enclosed in a block • the block defines a scope
  • 8. Compound Statements (2) • A BLOCK is delimited by curly brackets – {} • The braces are required • Perl offers several ways to write conditionals without curly brackets. • The continue BLOCK is always executed just before the conditional is about to be evaluated again. • A LABEL gives its associated control flow structure a name. if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK LABEL while (EXPR) BLOCK LABEL until (EXPR) BLOCK continue BLOCK LABEL for (EXPR; EXPR; EXPR) BLOCK LABEL foreach VAR (LIST) BLOCK continue BLOCK
  • 9. Compound Statements • Examples: use strict; use warnings; $ = $/; use strict; use warnings; $ = $/; unless( open(FH,$0)){ die 'I do not exist on disk!'. $^E } else { local $ = undef;#slurp mode my $c=1; print "$0: ", sprintf('%02d',$c++), " $_" while <FH>; } print $/.'---'; my $hashref = {me=>1,you=>2,he=>3}; exists $hashref->{she} and print 'she: '.$hashref->{she} or print 'she does not exists.' and print sort values %$hashref;
  • 10. Compound Statements (2) • Examples: my $c = 0; while ($c <= 10){ print $c; } continue { $c++; print $c; }; ######################################## A_LABEL: for my $m (1..10){ ANOTHER: for my $s(0..60) { last A_LABEL if $m > 4; last if $s > 4 and print '---'; print sprintf('%1$02d.%2$02d',$m,$s) ; } }
  • 11. Comments and POD • Text from a "#" character until the end of the line is a comment Exceptions include "#" inside a string or regular expression. • POD is a simple-to-use markup language used for writing documentation for Perl, Perl programs, and Perl modules. use strict; use warnings; $ = $/; my $simple = 'A simple statement.#not a comment.'; print $simple;#this is a comment $simple =~ s#a##ig; print $simple; $simple =~ s/#//ig; print $simple; =pod I like to use POD for multi-line comments but it is much more than that. =cut print $0 . ' finished.';
  • 12. Conditional Statements • Truth and Falsehood • if/elsif/unless/else • Statement modifiers (suffix notation)
  • 13. Conditional Statements • Truth and Falsehood • The number 0, the strings '0' and '', the empty list (), and undef are all false in a boolean context • All other values are true • Negation of a true value by ! or not returns a special false value. When evaluated as a string it is treated as '', but as a number, it is treated as 0.
  • 14. Conditional Statements • if/elsif/unless/else use strict; use warnings; $ = $/; unless( open(FH,$0) ){ die 'I do not exist on disk!'. $^E } else { local $ = undef; my $c = 1; print "$0: ", sprintf('%02d',$c++), " $_" while <FH>; } my $hashref = {me=>1,you=>2,he=>3}; if ( exists $hashref->{she} ) { print 'she:'.$hashref->{she}; } else { print 'she does not exists.'; print sort values %$hashref; }
  • 15. Conditional Statements • Statement modifiers (suffix notation) use strict; use warnings; $ = $/; { my $c=1; local $ = undef; do { print "$0: ", sprintf('%02d',$c++), " $_" while <FH> } if open(FH,$0) or die 'I do not exist on disk!'. $^E; } my $hashref = {me=>1,you=>2,he=>3}; print 'she:'.$hashref->{she} if ( exists $hashref->{she} ); do { print 'she does not exists.'; print sort values %$hashref; } unless exists $hashref->{she};
  • 16. Loops and Loop Control • Loops • for • foreach • while • until • do while/until
  • 17. Loops and Loop Control • for • Perl's C-style for loop works like the corresponding while loop for ($i = 1; $i < 10; $i++) { ... } is (almost) the same as $i = 1; while ($i < 10) { ... } continue { $i++; }
  • 18. Loops and Loop Control • foreach • Iterates over a normal list value and sets the variable VAR to be each element of the list in turn • If preceded with my, it is visible only within the loop • Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop • If VAR is omitted, $_ is set to each value • You can use foreach for readability or for for brevity
  • 19. Loops and Loop Control • foreach – Example: my @pets = qw|Goldy Amelia Jako|; my $favorite = 'Puffy';; foreach $favorite(@pets) { print 'My favourite pet is:' . $favorite; } print 'My favourite pet is:' . $favorite;#Puffy for $favorite(@pets) { print 'My favourite pet is:' . $favorite; } print 'My favourite pet is:' . $favorite;#Puffy unshift @pets,$favorite; for (@pets) { print 'My favourite pet is:' . $_; } #...
  • 20. Loops and Loop Control • while repeats a block of code as long as a condition is true • do while executes the do at least once before evaluating condition in while $|++;# enable $OUTPUT_AUTOFLUSH my @sufx = qw(th st nd rd th th th th th th th); my $i = 1; while ($i<=10) { print "This is $i$sufx[$i] iteration"; sleep 1; $i++; } do { print "The $i became $i" } while $i < 10; print '- ' x $c, $c and $c++ while ($c<=10);
  • 21. Loops and Loop Control • until repeats a block of code as long as a condition is NOT true • do until executes the do at least once before evaluating condition in until $|++;# enable $OUTPUT_AUTOFLUSH my @sufx = qw(th st nd rd th th th th th th th); $i = 10; until ($i<1) { print "This is $i$sufx[$i] countdown"; sleep 1; $i--; } do {print "T$i became $i"; $i--} until $i < 1;
  • 22. Loops and Loop Control • Loop control • next • last • redo • continue
  • 23. Loops and Loop Control • Loop control • next starts the next iteration of the loop (continue in C) • last immediately exits the loop (break in C) • redo restarts the loop block without evaluating the conditional again • continue is always executed just before the conditional is about to be evaluated again
  • 24. Loops and Loop Control • Loop control • next • If LABEL is omitted, refers to the innermost enclosing loop • cannot be used to exit a block which returns a value such as eval {}, sub {} or do {} • should not be used to exit a grep() or map() operation
  • 25. Loops and Loop Control (2) • Loop control • next my $c = 1; while (<DATA>){ next unless /perl/; chomp and print "$c: $_"; $c++; } __DATA__ This section of a perl file can be used by the perl program above in the same file to store and use some textual data perl rocks!!! Will the above line print if we remove this one?
  • 26. Loops and Loop Control • Loop control • last • If LABEL is omitted, refers to the innermost enclosing loop • cannot be used to exit a block which returns a value such as eval {}, sub {} or do {} • should not be used to exit a grep() or map() operation
  • 27. Loops and Loop Control (2) • Loop control • last my $c = 1; while (<DATA>){ last unless /perl/; chomp and print "$c: $_"; $c++; } __DATA__ This section of a perl file can be used by the perl program above in the same file to store and use some textual data perl rocks!!!
  • 28. Loops and Loop Control • Loop control • redo • skips the remaining BLOCK • does not execute any continue block (even if it exists) • If the LABEL is omitted, the command refers to the innermost enclosing loop • cannot be used to retry a block which returns a value such as eval {}, sub {} or do {} • should not be used to exit a grep() or map() operation
  • 29. Loops and Loop Control (2) • Loop control my ($c, $redone) = (1,0); • redo while (<DATA>){ chomp; print "$c: $_"; $c++; if ($_ =~ /perl/ and not $redone) { $redone++; redo; } elsif($_ =~ /perl/ and $redone) { $redone--; next; } } __DATA__ This section of a perl file can be used by the perl program above in the same file to store and use some textual data perl rocks!!!
  • 30. Loops and Loop Control • Loop control • continue • can be used to increment a loop variable, even when the loop has been continued via the next statement • last, next, or redo may appear within a continue block • last, next(!), and redo will behave as in the main block
  • 31. Loops and Loop Control • Loop control • continue my ($c,$reached_10) = (1,); while ($c) { print '- ' x $c, $c; } continue { last if ($c == 1 and $reached_10); $c-- if $reached_10; $c++ if $c < 10 and not $reached_10; $reached_10++ if $c == 10; }
  • 32. Logical Operators • &&/and • Binary "and" returns the logical conjunction of the two surrounding expressions. • and is equivalent to && except for the very low precedence • the right expression is evaluated only if the left expression is true my ($me,$you) = qw(me you); print 'We are here:'.($me && $you) if ($me && $you); print 'We are here:'.($me and $you) if ($me and $you); undef $me; print 'We are here:' if ($me and $you) or die 'Someone';
  • 33. Logical Operators • ||/or • Binary or returns the logical disjunction of the two surrounding expressions • or is equivalent to || except for the very low precedence • the right expression is evaluated only if the left expression is false • use or only for control flow
  • 34. Logical Operators • ||/or Example: my ($me,$you) = qw(me you); print 'Somebody is here:'.($me || $you) if ($me || $you); print 'Somebody is here:'.($me or $you) if ($me or $you); ($me,$you) = ('me', undef); print 'Somebody is here:'.($me or $you) if ($me or $you) or die 'Nooo..'; ($me,$you) = (undef, 'you'); print 'Somebody is here:'.($me or $you) if ($me or $you) or die 'no one';
  • 35. Logical Operators • !/not • Unary "not" returns the logical negation of the expression to its right • the equivalent of "!" except for the very low precedence use Config; print 'Do my perl uses old threads?'; print 'No' if !$Config{use5005threads}; print 'I do not have extras' if !$Config{extras}; print 'I do not have mail' if not $Config{mail};
  • 36. Logical Operators • The Ternary Operator, ?: • ?: is an if-then-else test, all in one expression • "ternary" – takes three operands • if the first expression is true, the second is evaluated, the third is ignored • if the first expression is false, the second is ignored, and the third is evaluated as the value of the whole 1 < 2 ? print 'true' : print 'false';
  • 37. Mathematical Operators • Additive Operators • Binary "+" returns the sum of two numbers • Binary "-" returns the difference of two numbers • Note: Binary "." concatenates two strings print 3+2; print 2-3; print 2.3; #;) print '2'.'3';
  • 38. Mathematical Operators • Multiplicative Operators • Binary "*" multiplies two numbers • Binary "/" divides two numbers • Binary "%" computes the modulus of two numbers • Binary "x" is the repetition operator print 3 * 2; print 2 / 3; print "oddn" if 3 % 2; #;) print 2 x 3;
  • 39. Mathematical Operators • Exponentiation • Binary "**" is the exponentiation operator • binds more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4 • Auto-increment and Auto-decrement • "++" and "--" work as in C print -2**4;#-16 my $a = 2; print $a++; #2 print ++$a; #4 print $a--; #4 print --$a; #2
  • 40. Operator Precedence and Associativity • Operator precedence means some operators are evaluated before others. • Operator associativity defines what happens if a sequence of the same operators is used one after another: whether the evaluator will evaluate the left operations first or the right. • See perlop/Operator Precedence and Associativity #precedence 2 + 4 * 5 == 2 + 20 == 22 and not 6 * 5 == 30 #associativity 8 - 4 – 2 == 4 - 2 == 2 and not 8 - 2 == 6
  • 41. Operator Precedence and Associativity • listed from highest precedence to lowest • operators borrowed from C keep the same precedence relationship with each other left terms and list operators (leftward) left -> nonassoc ++ -- right ** right ! ~ and unary + and - left =~ !~ left * / % x left + - . left << >> nonassoc named unary operators nonassoc < > <= >= lt gt le ge nonassoc == != <=> eq ne cmp ~~ ... to be continued
  • 42. Operator Precedence and Associativity (2) • Many operators can be overloaded for objects. • See the overload manpage ... continued left & left | ^ left && left || // nonassoc .. ... right ?: right = += -= *= etc. left , => nonassoc list operators (rightward) right not left and left or xor
  • 43. Error Handling • die • warn • eval{statements()}; do{something()} if($@) warn 'Default variable is undefined' unless $_; eval ' a syntax error or any failure'; if($@){ warn 'You spoiled everything'; }
  • 44. Error Handling • Carp • carp - warn of errors (from perspective of caller) • cluck - warn of errors with stack backtrace (not exported by default) • croak - die of errors (from perspective of caller) • confess - die of errors with stack backtrace
  • 45. Error Handling • Carp – Example: use Carp qw(cluck croak confess); other_place(); croak "We're outta here!"; sub here { $ARGV[0] ||= 'try'; if ($ARGV[0] =~ /try/){ cluck "nThis is how we got here!" } elsif ($ARGV[0] =~ /die/){ confess "nNothing to live for!"; } } sub there { here; } sub other_place { there }
  • 47. Exercises 1. Write a program that iterates from 3 to 15 and then from 15 to 3. Print every iteration on the screen. Try to write it from scratch. 2. Write a program that dies with an error message if the argument on the command line contains the word “die”. 3. Write a program that tries to guess the argument to the script if it contains the numbers 1 or 2 and prints different messages depending on the argument. Try not to use if/elsif/unless/else.