SlideShare a Scribd company logo
1 of 23
Download to read offline
Indian Institute of Technology Kharagpur



            PERL – Part II


          Prof. Indranil Sen Gupta
    Dept. of Computer Science & Engg.
           I.I.T. Kharagpur, INDIA




Lecture 22: PERL – Part II
On completion, the student will be able to:
• Define the file handling functions, and
   illustrate their use.
• Define the control structures in Perl, with
   illustrative examples.
• Define the relational operators and
   conditional statements.
• Illustrate the features using examples.




                                                 1
Sort the Elements of an Array

• Using the ‘sort’ keyword, by default we
  can sort the elements of an array
  lexicographically.
   Elements considered as strings.

    @colors = qw (red blue green black);
    @sort_col = sort @colors
         # Array @sort_col is (black blue green red)




   Another example:
     @num = qw (10 2 5 22 7 15);
     @new = sort @num;
       # @new will contain (10 15 2 22 5 7)


   How do sort numerically?
     @num = qw (10 2 5 22 7 15);
     @new = sort {$a <=> $b} @num;
       # @new will contain (2 5 7 10 15 22)




                                                       2
The ‘splice’ function

• Arguments to the ‘splice’ function:
   The first argument is an array.
   The second argument is an offset (index
   number of the list element to begin
   splicing at).
   Third argument is the number of elements
   to remove.
    @colors = (“red”, “green”, “blue”, “black”);
    @middle = splice (@colors, 1, 2);
       # @middle contains the elements removed




            File Handling




                                                   3
Interacting with the user

• Read from the keyboard (standard
  input).
     Use the file handle <STDIN>.
     Very simple to use.
      print “Enter your name: ”;
      $name = <STDIN>;     # Read from keyboard
      print “Good morning, $name. n”;


     $name also contains the newline character.
       Need to chop it off.




               The ‘chop’ Function

• The ‘chop’ function removes the last character of
  whatever it is given to chop.
• In the following example, it chops the newline.

      print “Enter your name: ”;
      chop ($name = <STDIN>);
           # Read from keyboard and chop newline
      print “Good morning, $name. n”;


• ‘chop’ removes the last character irrespective
  of whether it is a newline or not.
     Sometimes dangerous.




                                                      4
Safe chopping: ‘chomp’

• The ‘chomp’ function works similar to
  ‘chop’, with the difference that it chops off
  the last character only if it is a newline.
     print “Enter your name: ”;
     chomp ($name = <STDIN>);
          # Read from keyboard and chomp newline
     print “Good morning, $name. n”;




                  File Operations

• Opening a file
    The ‘open’ command opens a file and
    returns a file handle.
    For standard input, we have a predefined
    handle <STDIN>.
     $fname = “/home/isg/report.txt”;
     open XYZ , $fname;
     while (<XYZ>) {
        print “Line number $. : $_”;
     }




                                                   5
Checking the error code:

    $fname = “/home/isg/report.txt”;
    open XYZ, $fname or die “Error in open: $!”;
    while (<XYZ>) {
       print “Line number $. : $_”;
    }


   $.       returns the line number (starting at 1)
   $_       returns the contents of last match
   $i       returns the error code/message




• Reading from a file:
   The last example also illustrates file
   reading.
   The angle brackets (< >) are the line input
   operators.
        The data read goes into $_




                                                      6
• Writing into a file:

     $out = “/home/isg/out.txt”;
     open XYZ , “>$out” or die “Error in write: $!”;
     for $i (1..20) {
        print XYZ “$i :: Hello, the time is”,
                          scalar(localtime), “n”;
     }




• Appending to a file:

     $out = “/home/isg/out.txt”;
     open XYZ , “>>$out” or die “Error in write: $!”;
     for $i (1..20) {
        print XYZ “$i :: Hello, the time is”,
                          scalar(localtime), “n”;
     }




                                                        7
• Closing a file:
      close XYZ;
    where XYZ is the file handle of the file
    being closed.




• Printing a file:
    This is very easy to do in Perl.

     $input = “/home/isg/report.txt”;
     open IN, $input or die “Error in open: $!”;
     while (<IN>) {
        print;
     }
     close IN;




                                                   8
Command Line Arguments

• Perl uses a special array called @ARGV.
   List of arguments passed along with the
   script name on the command line.
   Example: if you invoke Perl as:
     perl test.pl red blue green
   then @ARGV will be (red blue green).
   Printing the command line arguments:
     foreach (@ARGV) {
        print “$_ n”;
     }




            Standard File Handles

• <STDIN>
   Read from standard input (keyboard).
• <STDOUT>
   Print to standard output (screen).
• <STDERR>
   For outputting error messages.
• <ARGV>
   Reads the names of the files from the
   command line and opens them all.




                                             9
@ARGV array contains the text after the
program’s name in command line.
  <ARGV> takes each file in turn.
  If there is nothing specified on the command
  line, it reads from the standard input.
Since this is very commonly used, Perl
provides an abbreviation for <ARGV>,
namely, < >
An example is shown.




 $lineno = 1;
 while (< >) {
    print $lineno ++;
    print “$lineno: $_”;
 }


In this program, the name of the file has
to be given on the command line.
  perl list_lines.pl file1.txt
  perl list_lines.pl a.txt b.txt c.txt




                                                 10
Control Structures




                      Introduction

• There are many control constructs in
  Perl.
   Similar to those in C.
   Would be illustrated through examples.
   The available constructs:
     for
     foreach
     if/elseif/else
     while
     do, etc.




                                            11
Concept of Block

• A statement block is a sequence of
  statements enclosed in matching pair
  of { and }.

     if (year == 2000) {
       print “You have entered new millenium.n”;
     }


• Blocks may be nested within other
  blocks.




          Definition of TRUE in Perl

• In Perl, only three things are
  considered as FALSE:
    The value 0
    The empty string (“ ”)
    undef
• Everything else in Perl is TRUE.




                                                    12
if .. else

• General syntax:

   if (test expression) {
     # if TRUE, do this
   }
   else {
     # if FALSE, do this
   }




• Examples:
   if ($name eq ‘isg’) {
      print “Welcome Indranil. n”;
    } else {
          print “You are somebody else. n”;
    }

    if ($flag == 1) {
       print “There has been an error. n”;
    }
         # The else block is optional




                                               13
elseif

• Example:
    print “Enter your id: ”;
    chomp ($name = <STDIN>);
    if ($name eq ‘isg’) {
          print “Welcome Indranil. n”;
    } elseif ($name eq ‘bkd’) {
          print “Welcome Bimal. n”;
    } elseif ($name eq ‘akm’) {
          print “Welcome Arun. n”;
    } else {
          print “Sorry, I do not know you. n”;
    }




                          while

• Example: (Guessing the correct word)
  $your_choice = ‘ ‘;
  $secret_word = ‘India’;
  while ($your_choice ne $secret_word) {
    print “Enter your guess: n”;
    chomp ($your_choice = <STDIN>);
  }

  print “Congratulations! Mera Bharat Mahan.”




                                                  14
for

• Syntax same as in C.
• Example:

     for ($i=1; $i<10; $i++) {
       print “Iteration number $i n”;
     }




                         foreach

• Very commonly used function that
  iterates over a list.
• Example:

     @colors = qw (red blue green);
     foreach $name (@colors) {
       print “Color is $name. n”;
     }


• We can use ‘for’ in place of ‘foreach’.




                                            15
• Example: Counting odd numbers in a list
  @xyz = qw (10 15 17 28 12 77 56);
  $count = 0;

  foreach $number (@xyz) {
    if (($number % 2) == 1) {
       print “$number is odd. n”;
       $count ++;
    }
    print “Number of odd numbers is $count. n”;
  }




            Breaking out of a loop

• The statement ‘last’, if it appears in
  the body of a loop, will cause Perl to
  immediately exit the loop.
    Used with a conditional.
     last if (i > 10);




                                                   16
Skipping to end of loop

• For this we use the statement ‘next’.
   When executed, the remaining
   statements in the loop will be skipped,
   and the next iteration will begin.
   Also used with a conditional.




      Relational Operators




                                             17
The Operators Listed

  Comparison       Numeric       String

     Equal           ==           eq

   Not equal         !=           ne

  Greater than        >            gt

   Less than          <            lt

Greater or equal     >=           ge

 Less or equal       <=            le




             Logical Connectives

• If $a and $b are logical expressions,
  then the following conjunctions are
  supported by Perl:
   $a and $b          $a && $b
   $a or $b           $a || $b
   not $a             ! $a
• Both the above alternatives are
  equivalent; first one is more readable.




                                            18
SOLUTIONS TO QUIZ
  QUESTIONS ON
   LECTURE 21




                    19
Quiz Solutions on Lecture 21
1. Do you need to compile a Perl program?
     No, Perl works in interpretive mode. You just
     need a Perl interpreter.
2. When you are writing a Perl program for a
   Unix platform, what do the first line
   #!/usr/bin/perl indicate?
     The first line indicates the full path name of the
     Perl interpreter.
3. Why is Perl called a loosely typed
   language?
     Because by default data types are not assigned
     to variables.




     Quiz Solutions on Lecture 21

4. A string can be enclosed within single
   quotes or double quotes. What is the
   difference?
     If it is enclosed within double quotes, it
     means that variable interpolation is in
     effect.
5. How do you concatenate two strings?
   Give an example.
     By using the dot(.) operator.
      $newstring = $a . $b . $c;




                                                          20
Quiz Solutions on Lecture 21
6. What is the meaning of adding a number to
   a string?
     The number gets added to the ASCII
     value.
7. What is the convenient construct to print a
   number of fixed strings?
     Using line-oriented quoting
        (print << somestring).
8. How do you add a scalar at the beginning
   of an array?
      @xyz = (10, @xyz);




     Quiz Solutions on Lecture 21

9. How do you concatenate two arrays and
    form a third array?
      @third = (@first, @second);
10. How do you reverse an array?
      @xyz = reverse @original;
11. How do you print the elements of an array?
      print “@arrayname”;




                                                 21
QUIZ QUESTIONS ON
          LECTURE 22




     Quiz Questions on Lecture 21

1. How to sort the elements of an array in the
   numerical order?
2. Write a Perl program segment to sort an
   array in the descending order.
3. What is the difference between the functions
   ‘chop’ and ‘chomp’?
4. Write a Perl program segment to read a text
   file “input.txt”, and generate as output
   another file “out.txt”, where a line number
   precedes all the lines.
5. How does Perl check if the result of a
   relational expression is TRUE of FALSE.




                                                  22
Quiz Questions on Lecture 21

6. For comparison, what is the difference
   between “lt” and “<“?
7. What is the significance of the file handle
   <ARGV>?
8. How can you exit a loop in Perl based on
   some condition?




                                                 23

More Related Content

What's hot (20)

Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
String variable in php
String variable in phpString variable in php
String variable in php
 
Perl programming language
Perl programming languagePerl programming language
Perl programming language
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Introduction to Perl - Day 1
Introduction to Perl - Day 1Introduction to Perl - Day 1
Introduction to Perl - Day 1
 
Introduction in php
Introduction in phpIntroduction in php
Introduction in php
 
Perl Introduction
Perl IntroductionPerl Introduction
Perl Introduction
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
Class 2 - Introduction to PHP
Class 2 - Introduction to PHPClass 2 - Introduction to PHP
Class 2 - Introduction to PHP
 
Practical approach to perl day1
Practical approach to perl day1Practical approach to perl day1
Practical approach to perl day1
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
Perl
PerlPerl
Perl
 
Unit vii wp ppt
Unit vii wp pptUnit vii wp ppt
Unit vii wp ppt
 
Perl Basics with Examples
Perl Basics with ExamplesPerl Basics with Examples
Perl Basics with Examples
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Functions in PHP
Functions in PHPFunctions in PHP
Functions in PHP
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 

Viewers also liked

Capitulo i tucker
Capitulo i tuckerCapitulo i tucker
Capitulo i tuckerdavihg
 
Lecture 23
Lecture 23Lecture 23
Lecture 23rhshriva
 
Marketing Plan VSI BY Ayovsi.com
Marketing Plan VSI BY Ayovsi.comMarketing Plan VSI BY Ayovsi.com
Marketing Plan VSI BY Ayovsi.comAgus Chandra
 
Garfield's Short Life
Garfield's Short LifeGarfield's Short Life
Garfield's Short Lifealimae
 
Strategies for Acing Interviews
Strategies for Acing InterviewsStrategies for Acing Interviews
Strategies for Acing InterviewsKazi Mashrur Mamun
 
Pink day 2010
Pink day 2010Pink day 2010
Pink day 2010Bak32005
 
The Self Marketing Firm
The Self Marketing FirmThe Self Marketing Firm
The Self Marketing Firmselfpromo1
 
Strategy Proposal: IKEA
Strategy Proposal: IKEAStrategy Proposal: IKEA
Strategy Proposal: IKEARina22
 
Movable Type 6の新機能 Data APIの活用法
Movable Type 6の新機能 Data APIの活用法Movable Type 6の新機能 Data APIの活用法
Movable Type 6の新機能 Data APIの活用法Hajime Fujimoto
 
Movable Type 6.0をできるだけ安く使う方法
Movable Type 6.0をできるだけ安く使う方法Movable Type 6.0をできるだけ安く使う方法
Movable Type 6.0をできるだけ安く使う方法Hajime Fujimoto
 
Liderazgo consciente nov 14
Liderazgo consciente nov 14Liderazgo consciente nov 14
Liderazgo consciente nov 14Chomin Alonso
 
Mind flow. expertos en procesos de cambio y mejora
Mind flow. expertos en procesos de cambio y mejoraMind flow. expertos en procesos de cambio y mejora
Mind flow. expertos en procesos de cambio y mejoraChomin Alonso
 
JavaScriptテンプレートエンジンで活かすData API
JavaScriptテンプレートエンジンで活かすData APIJavaScriptテンプレートエンジンで活かすData API
JavaScriptテンプレートエンジンで活かすData APIHajime Fujimoto
 
PHPやVBAでMovable Typeを操作しようData API Library for PHP/VBAのご紹介
PHPやVBAでMovable Typeを操作しようData API Library for PHP/VBAのご紹介PHPやVBAでMovable Typeを操作しようData API Library for PHP/VBAのご紹介
PHPやVBAでMovable Typeを操作しようData API Library for PHP/VBAのご紹介Hajime Fujimoto
 
Objecttreeプラグイン&ObjectRelationプラグインのご紹介
Objecttreeプラグイン&ObjectRelationプラグインのご紹介Objecttreeプラグイン&ObjectRelationプラグインのご紹介
Objecttreeプラグイン&ObjectRelationプラグインのご紹介Hajime Fujimoto
 
Movable Typeの権限と承認フロー
Movable Typeの権限と承認フローMovable Typeの権限と承認フロー
Movable Typeの権限と承認フローHajime Fujimoto
 

Viewers also liked (20)

Capitulo i tucker
Capitulo i tuckerCapitulo i tucker
Capitulo i tucker
 
情報処理第5回
情報処理第5回情報処理第5回
情報処理第5回
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
 
Marketing Plan VSI BY Ayovsi.com
Marketing Plan VSI BY Ayovsi.comMarketing Plan VSI BY Ayovsi.com
Marketing Plan VSI BY Ayovsi.com
 
Garfield's Short Life
Garfield's Short LifeGarfield's Short Life
Garfield's Short Life
 
Strategies for Acing Interviews
Strategies for Acing InterviewsStrategies for Acing Interviews
Strategies for Acing Interviews
 
Resume
ResumeResume
Resume
 
Pink day 2010
Pink day 2010Pink day 2010
Pink day 2010
 
The Self Marketing Firm
The Self Marketing FirmThe Self Marketing Firm
The Self Marketing Firm
 
Strategy Proposal: IKEA
Strategy Proposal: IKEAStrategy Proposal: IKEA
Strategy Proposal: IKEA
 
Movable Type 6の新機能 Data APIの活用法
Movable Type 6の新機能 Data APIの活用法Movable Type 6の新機能 Data APIの活用法
Movable Type 6の新機能 Data APIの活用法
 
Movable Type 6.0をできるだけ安く使う方法
Movable Type 6.0をできるだけ安く使う方法Movable Type 6.0をできるだけ安く使う方法
Movable Type 6.0をできるだけ安く使う方法
 
Game Pitches
Game PitchesGame Pitches
Game Pitches
 
Liderazgo consciente nov 14
Liderazgo consciente nov 14Liderazgo consciente nov 14
Liderazgo consciente nov 14
 
Mind flow. expertos en procesos de cambio y mejora
Mind flow. expertos en procesos de cambio y mejoraMind flow. expertos en procesos de cambio y mejora
Mind flow. expertos en procesos de cambio y mejora
 
JavaScriptテンプレートエンジンで活かすData API
JavaScriptテンプレートエンジンで活かすData APIJavaScriptテンプレートエンジンで活かすData API
JavaScriptテンプレートエンジンで活かすData API
 
PHPやVBAでMovable Typeを操作しようData API Library for PHP/VBAのご紹介
PHPやVBAでMovable Typeを操作しようData API Library for PHP/VBAのご紹介PHPやVBAでMovable Typeを操作しようData API Library for PHP/VBAのご紹介
PHPやVBAでMovable Typeを操作しようData API Library for PHP/VBAのご紹介
 
Connect with Data API
Connect with Data APIConnect with Data API
Connect with Data API
 
Objecttreeプラグイン&ObjectRelationプラグインのご紹介
Objecttreeプラグイン&ObjectRelationプラグインのご紹介Objecttreeプラグイン&ObjectRelationプラグインのご紹介
Objecttreeプラグイン&ObjectRelationプラグインのご紹介
 
Movable Typeの権限と承認フロー
Movable Typeの権限と承認フローMovable Typeの権限と承認フロー
Movable Typeの権限と承認フロー
 

Similar to Lecture 22

Perl courseparti
Perl coursepartiPerl courseparti
Perl coursepartiernlow
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Andrea Telatin
 
Scripting3
Scripting3Scripting3
Scripting3Nao Dara
 
Perl training-in-navi mumbai
Perl training-in-navi mumbaiPerl training-in-navi mumbai
Perl training-in-navi mumbaivibrantuser
 
Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...
Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...
Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...Andrea Telatin
 
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
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation TutorialLorna Mitchell
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationMohammed Farrag
 
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Workhorse Computing
 
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
 

Similar to Lecture 22 (20)

Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
 
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
Bioinformatica: Esercizi su Perl, espressioni regolari e altre amenità (BMR G...
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
tutorial7
tutorial7tutorial7
tutorial7
 
tutorial7
tutorial7tutorial7
tutorial7
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Scripting3
Scripting3Scripting3
Scripting3
 
Perl slid
Perl slidPerl slid
Perl slid
 
Perl intro
Perl introPerl intro
Perl intro
 
Perl training-in-navi mumbai
Perl training-in-navi mumbaiPerl training-in-navi mumbai
Perl training-in-navi mumbai
 
Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...
Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...
Bioinformatica: Leggere file con Perl, e introduzione alle espressioni regola...
 
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
 
Dades i operadors
Dades i operadorsDades i operadors
Dades i operadors
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Lecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administrationLecture 3 Perl & FreeBSD administration
Lecture 3 Perl & FreeBSD administration
 
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent. Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
Our Friends the Utils: A highway traveled by wheels we didn't re-invent.
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 

Lecture 22

  • 1. Indian Institute of Technology Kharagpur PERL – Part II Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Kharagpur, INDIA Lecture 22: PERL – Part II On completion, the student will be able to: • Define the file handling functions, and illustrate their use. • Define the control structures in Perl, with illustrative examples. • Define the relational operators and conditional statements. • Illustrate the features using examples. 1
  • 2. Sort the Elements of an Array • Using the ‘sort’ keyword, by default we can sort the elements of an array lexicographically. Elements considered as strings. @colors = qw (red blue green black); @sort_col = sort @colors # Array @sort_col is (black blue green red) Another example: @num = qw (10 2 5 22 7 15); @new = sort @num; # @new will contain (10 15 2 22 5 7) How do sort numerically? @num = qw (10 2 5 22 7 15); @new = sort {$a <=> $b} @num; # @new will contain (2 5 7 10 15 22) 2
  • 3. The ‘splice’ function • Arguments to the ‘splice’ function: The first argument is an array. The second argument is an offset (index number of the list element to begin splicing at). Third argument is the number of elements to remove. @colors = (“red”, “green”, “blue”, “black”); @middle = splice (@colors, 1, 2); # @middle contains the elements removed File Handling 3
  • 4. Interacting with the user • Read from the keyboard (standard input). Use the file handle <STDIN>. Very simple to use. print “Enter your name: ”; $name = <STDIN>; # Read from keyboard print “Good morning, $name. n”; $name also contains the newline character. Need to chop it off. The ‘chop’ Function • The ‘chop’ function removes the last character of whatever it is given to chop. • In the following example, it chops the newline. print “Enter your name: ”; chop ($name = <STDIN>); # Read from keyboard and chop newline print “Good morning, $name. n”; • ‘chop’ removes the last character irrespective of whether it is a newline or not. Sometimes dangerous. 4
  • 5. Safe chopping: ‘chomp’ • The ‘chomp’ function works similar to ‘chop’, with the difference that it chops off the last character only if it is a newline. print “Enter your name: ”; chomp ($name = <STDIN>); # Read from keyboard and chomp newline print “Good morning, $name. n”; File Operations • Opening a file The ‘open’ command opens a file and returns a file handle. For standard input, we have a predefined handle <STDIN>. $fname = “/home/isg/report.txt”; open XYZ , $fname; while (<XYZ>) { print “Line number $. : $_”; } 5
  • 6. Checking the error code: $fname = “/home/isg/report.txt”; open XYZ, $fname or die “Error in open: $!”; while (<XYZ>) { print “Line number $. : $_”; } $. returns the line number (starting at 1) $_ returns the contents of last match $i returns the error code/message • Reading from a file: The last example also illustrates file reading. The angle brackets (< >) are the line input operators. The data read goes into $_ 6
  • 7. • Writing into a file: $out = “/home/isg/out.txt”; open XYZ , “>$out” or die “Error in write: $!”; for $i (1..20) { print XYZ “$i :: Hello, the time is”, scalar(localtime), “n”; } • Appending to a file: $out = “/home/isg/out.txt”; open XYZ , “>>$out” or die “Error in write: $!”; for $i (1..20) { print XYZ “$i :: Hello, the time is”, scalar(localtime), “n”; } 7
  • 8. • Closing a file: close XYZ; where XYZ is the file handle of the file being closed. • Printing a file: This is very easy to do in Perl. $input = “/home/isg/report.txt”; open IN, $input or die “Error in open: $!”; while (<IN>) { print; } close IN; 8
  • 9. Command Line Arguments • Perl uses a special array called @ARGV. List of arguments passed along with the script name on the command line. Example: if you invoke Perl as: perl test.pl red blue green then @ARGV will be (red blue green). Printing the command line arguments: foreach (@ARGV) { print “$_ n”; } Standard File Handles • <STDIN> Read from standard input (keyboard). • <STDOUT> Print to standard output (screen). • <STDERR> For outputting error messages. • <ARGV> Reads the names of the files from the command line and opens them all. 9
  • 10. @ARGV array contains the text after the program’s name in command line. <ARGV> takes each file in turn. If there is nothing specified on the command line, it reads from the standard input. Since this is very commonly used, Perl provides an abbreviation for <ARGV>, namely, < > An example is shown. $lineno = 1; while (< >) { print $lineno ++; print “$lineno: $_”; } In this program, the name of the file has to be given on the command line. perl list_lines.pl file1.txt perl list_lines.pl a.txt b.txt c.txt 10
  • 11. Control Structures Introduction • There are many control constructs in Perl. Similar to those in C. Would be illustrated through examples. The available constructs: for foreach if/elseif/else while do, etc. 11
  • 12. Concept of Block • A statement block is a sequence of statements enclosed in matching pair of { and }. if (year == 2000) { print “You have entered new millenium.n”; } • Blocks may be nested within other blocks. Definition of TRUE in Perl • In Perl, only three things are considered as FALSE: The value 0 The empty string (“ ”) undef • Everything else in Perl is TRUE. 12
  • 13. if .. else • General syntax: if (test expression) { # if TRUE, do this } else { # if FALSE, do this } • Examples: if ($name eq ‘isg’) { print “Welcome Indranil. n”; } else { print “You are somebody else. n”; } if ($flag == 1) { print “There has been an error. n”; } # The else block is optional 13
  • 14. elseif • Example: print “Enter your id: ”; chomp ($name = <STDIN>); if ($name eq ‘isg’) { print “Welcome Indranil. n”; } elseif ($name eq ‘bkd’) { print “Welcome Bimal. n”; } elseif ($name eq ‘akm’) { print “Welcome Arun. n”; } else { print “Sorry, I do not know you. n”; } while • Example: (Guessing the correct word) $your_choice = ‘ ‘; $secret_word = ‘India’; while ($your_choice ne $secret_word) { print “Enter your guess: n”; chomp ($your_choice = <STDIN>); } print “Congratulations! Mera Bharat Mahan.” 14
  • 15. for • Syntax same as in C. • Example: for ($i=1; $i<10; $i++) { print “Iteration number $i n”; } foreach • Very commonly used function that iterates over a list. • Example: @colors = qw (red blue green); foreach $name (@colors) { print “Color is $name. n”; } • We can use ‘for’ in place of ‘foreach’. 15
  • 16. • Example: Counting odd numbers in a list @xyz = qw (10 15 17 28 12 77 56); $count = 0; foreach $number (@xyz) { if (($number % 2) == 1) { print “$number is odd. n”; $count ++; } print “Number of odd numbers is $count. n”; } Breaking out of a loop • The statement ‘last’, if it appears in the body of a loop, will cause Perl to immediately exit the loop. Used with a conditional. last if (i > 10); 16
  • 17. Skipping to end of loop • For this we use the statement ‘next’. When executed, the remaining statements in the loop will be skipped, and the next iteration will begin. Also used with a conditional. Relational Operators 17
  • 18. The Operators Listed Comparison Numeric String Equal == eq Not equal != ne Greater than > gt Less than < lt Greater or equal >= ge Less or equal <= le Logical Connectives • If $a and $b are logical expressions, then the following conjunctions are supported by Perl: $a and $b $a && $b $a or $b $a || $b not $a ! $a • Both the above alternatives are equivalent; first one is more readable. 18
  • 19. SOLUTIONS TO QUIZ QUESTIONS ON LECTURE 21 19
  • 20. Quiz Solutions on Lecture 21 1. Do you need to compile a Perl program? No, Perl works in interpretive mode. You just need a Perl interpreter. 2. When you are writing a Perl program for a Unix platform, what do the first line #!/usr/bin/perl indicate? The first line indicates the full path name of the Perl interpreter. 3. Why is Perl called a loosely typed language? Because by default data types are not assigned to variables. Quiz Solutions on Lecture 21 4. A string can be enclosed within single quotes or double quotes. What is the difference? If it is enclosed within double quotes, it means that variable interpolation is in effect. 5. How do you concatenate two strings? Give an example. By using the dot(.) operator. $newstring = $a . $b . $c; 20
  • 21. Quiz Solutions on Lecture 21 6. What is the meaning of adding a number to a string? The number gets added to the ASCII value. 7. What is the convenient construct to print a number of fixed strings? Using line-oriented quoting (print << somestring). 8. How do you add a scalar at the beginning of an array? @xyz = (10, @xyz); Quiz Solutions on Lecture 21 9. How do you concatenate two arrays and form a third array? @third = (@first, @second); 10. How do you reverse an array? @xyz = reverse @original; 11. How do you print the elements of an array? print “@arrayname”; 21
  • 22. QUIZ QUESTIONS ON LECTURE 22 Quiz Questions on Lecture 21 1. How to sort the elements of an array in the numerical order? 2. Write a Perl program segment to sort an array in the descending order. 3. What is the difference between the functions ‘chop’ and ‘chomp’? 4. Write a Perl program segment to read a text file “input.txt”, and generate as output another file “out.txt”, where a line number precedes all the lines. 5. How does Perl check if the result of a relational expression is TRUE of FALSE. 22
  • 23. Quiz Questions on Lecture 21 6. For comparison, what is the difference between “lt” and “<“? 7. What is the significance of the file handle <ARGV>? 8. How can you exit a loop in Perl based on some condition? 23