SlideShare a Scribd company logo
1 of 47
Download to read offline
Perl Tutorial
    Pablo Manalastas <pmanalastas@ateneo.edu> 




      LEARNING PERL


                         
Numbers
    ●   Numbers are double precision floating point 
        values (double in C)
        3,  1.5,  2.7e8,  2_427_132_115,
        0577, 0xf3ab, 0b1110001011
    ●   Numeric operations
        Add (+), subtract (­), negate (­), multiply (*), 
        divide (/), modulus (%)
        3 + 4.2,   2.3e4*6.2523,  10%4


                                  
Strings
    ●   Can be any length & can contain any characters
    ●   Single­quoted strings
        'Pablo de Gracia, Jr.'
        'The winter of our discontent.'
        'Queen's Jewels'
        # the single quote ' is specified as '
        'The backslash  is special'
        # the backslash  is specified as 


                              
Strings
●   Double­quoted strings
    ”against earth's flowing breast”
    “I am called ”handsome” by some”
    “I came.nI saw.nI conquered.n”
    “Tabtseparatedtentriesthere”
●   String concatenation
    “Hello ”  .  “worldn”
●   String repetition
    “maganda ” x 3

                         
Autoconversion: Numbers & Strings
    ●   Arithmetic operations (+,­,*,/,%) convert strings 
        to numbers
        “12plus2” + “3”   # gives the number 15
    ●   String operation (.) converts numbers to strings
        “XJW” . 24*5  # gives the string “XJW120”




                                 
Variables

    ●   Variable names
        [$@%][A­Za­z_][0­9A­Za­z_]*
    ●   Scalar variables, name starts with $
        –   Holds one value (scalar value)
        –   Examples:
            $daily_rate = 350.00;
            $horse_name = “Heaven's Pride”;
            $monthly_pay = $daily_rate * 22;

                                   
Binary Assignment Operators
    ●   Replace $var = $var op $val;
            by $var op= $val;
    ●   Examples:
        $new_rate += 12;
        $quotient /= 10;
        $name .= “, PhD”;
        $balance ­= $withdrawal;



                          
Output Using “print”
    ●   Write output to stdout using print

        print “Hello, world!n”;
        print “The answer is ” . 350 * 6 . 
        “n”;
        print “The answer is ”, 350 * 6,
        “n”;



                               
Interpolation
    ●   Interpolation: the replacement of a scalar 
        variable by its value in a double quoted string or 
        when occuring alone
    ●   Examples
        $meal = 'beef steak';
        print “Juan ate $mealn”;
        print “I like $meal for dinnern”;
        print “Juan's dinner is “ . $meal;
        print “Juan's dinner is “, $meal;

                                
Delimiting the Variable Name
    ●   Use { } to delimit the variable name to be 
        interpolated
    ●   Examples
        $what = 'steak';
        print “I love all kinds of ${what}sn”;
        print “I love all kinds of $what”, “sn”;
        print “Prime rib is the $what of ${what}sn”;



                                 
Comparison Operators
    ●   Numeric comparison operators
        ==, !=, <, >, <=, >=
        Examples:
        50 == 100/2; # true
        100/3 != 33.3 # true
    ●   String comparison operators
        eq, ne, lt, gt, le, ge
        'pedro' lt 'jose' # false
        'jose' eq “jose” # true
 
        ' ' gt '' # true      
Boolean Values
    ●   undef, number zero (0), string zero ('0'), the 
        empty string (''), are all false. Undef designates 
        a variable with no value assigned yet.
    ●   non­zero numbers (like 1) and non­empty 
        strings (except '0') are all true. 
    ●   Examples
        $bool1 = 'Fred' lt 'fred';
        $bool2 = 'fred' lt 'Fred';
        print $bool1;   # prints 1 for true
        print $bool2;   # empty string for false
                                 
If Control Structure
    ●   Syntax
        if( condition ) { true­part; } else { false­part; }
    ●   Example
        $disc = $b*$b – 4.0*$a*$c;
        if( $disc >= 0.0 ) {
          print “Real rootsn”;
        } else {
          print “Complex rootsn”;
        }

                                   
Reading One Line from Stdin
    ●   Use <STDIN> to read one line from standard 
        input, usually the console keyboard
    ●   Examples:
        print “Enter first name: “;
        $fname = <STDIN>;
        print “Enter last name: “;
        $lname = <STDIN>;
        chomp($fname);
        chomp($lname);
        print “Your name: $fname $lnamen”;
                              
The chomp() Function
    ●   chomp() removes a trailing newline 'n' from the 
        string value of a variable
    ●   Version2 of program:
        print “Enter first name: “;
        chomp($fname = <STDIN>);
        print “Enter last name: “;
        chomp($lname = <STDIN>);
        print “Your name: $fname $lnamen”;


                                
While Control Structure
    ●   Syntax:
        initialization;
        while ( condition ) {
           statements;
           reinitialization;
        }
    ●   Example:
        $i = 1;
        while($i <= 10) {
          print “Counting $in”;
          ++$i;
        }
                                 
UNDEF
    ●   If an undefined variable is used as a number, 
        undef is like zero (0). If used as a string, undef 
        is like the empty string ('')
    ●   If $x is undefined, the following are allowed:
        $x += 2;
        $x .= 'bye';
    ●   If $x has a value, then
        $x = undef;
        makes $x undefined
                                   
The defined() Function
    ●   The <STDIN> operation may return the value 
        undef when there is no more input, such as at 
        end­of­file
    ●   The function defined() can test if <STDIN> read 
        one line of input from standard input.
    ●   Example
        while(defined($line = <STDIN>)) {
          print “You typed: $line”;
        }
        print “No more inputn”;
                               
Exercises
    ●   Write a Perl program that reads lines of input 
        from <STDIN>, and prints each line read. Stop 
        when the line that is read is 'Done' (without the 
        quotes).
    ●   Write a Perl program that reads the values of 
        three variables $num1, $oper, and $num2 from 
        <STDIN>.  If the value of $oper is one of the 
        strings 'plus', 'minus', 'times', or 'over', the 
        program should carry out the indicated 
        operation on $num1 and $num2.
                                
Lists & Arrays 
    ●   List: an ordered collection of scalar values. The 
        index is the position of a scalar value in the list. 
        The index runs from 0 to (n­1), where n is the 
        size of the list. An array is a variable that 
        contains a list, and starts with a @sign
    ●   Example:
        @quals
        @friends

                                  
Initializing Arrays with Literal Values
    ●   An array may be initialized with values in 
        parentheses ( ). Example: 
        @propty = ('Pablo', 62, 'male', 
        undef);

        Here, the array is @propty, and the values in 
        the list are:
        $propty[0] is 'Pablo'
        $propty[1] is 62
        $propty[2] is 'male'
        $propty[3] is undef  #civil status
                               
Values May All Be Same Type
    ●   All list values may be the same type
        @friends = ('Pablo', 'Jose', 
        'Juan', 'Mario', 'David');

        Here, the array is @friends, and the values in 
        the list are:
        $friends[0] is 'Pablo'
        $friends[1] is 'Jose'
        $friends[2] is 'Juan'
        $friends[3] is 'Mario'
        $friends[4] is 'David'
                               
Values of Array Indices
    ●   Any value, variable, or expression, whose value is 
        integer or can be converted to integer can be used as 
        index.
    ●   Example:
        $ndx = 2.5;
        $friends[$ndx+1] is $friends[3]
    ●   $#friends is the value of the last index of array 
        @friends, which is 4.
    ●   $friends[$#friends+10] = 'Carlos';
        adds element 'Carlos' at index 14, the 15th element. 
        Values at index 5 to 13 will be undef.
                                  
Initializing Array with Literal Values
    ●   @arr = ( );
        @arr = (5..10, 17, 21);
        @arr = ($a..$b);
        @arr = qw/  Pablo Jose Mario /;
        @arr = qw! Pablo Jose Mario !;
        @arr = qw( Pablo Jose Mario );
        @arr = qw{ Pablo Jose Mario };
        @arr = qw< Pablo Jose Mario >;



                         
Interpolate Arrays/Values in Strings
    ●   If @arr is an array, then array @arr and list 
        value $arr[k] will be interpolated (evaluated) 
        when placed inside double quoted strings
    ●   Example interpolating arrays
        @arr = (5..7);
        print “Four @arr eightn”;
        # will print Four 5 6 7 eight
    ●   Example interpolating list values
        @toy = ('toycar', 'toyrobot', 
        'toygun');
 
        print “I have a $toy[2] at homen”;
                                
pop( ) Function
    ●   pop() removes the rightmost list value from an 
        array
    ●   Example:
        @stk = (5..9);
        $a = pop(@stk);
        # remove 9 leaving 5..8, $a = 9
        $b = pop @stk;
        # remove 8 leaving 5..7, $b = 8
        pop @stk;    # remove 7 leaving 5..6
                                
push() Function
    ●   push(): adds new rightmost values to the list of 
        an array
    ●   Example:
        @stk = (5..8);
        push(@stk, 0);  # now (5,6,7,8,0)
        push @stk, (1..3);# now (5,6,7,8,0,1,2,3)
        @stk2 = qw/ 10 11 12 /;
        push @stk, @stk2; 
        # now (5,6,7,8,0,1,2,3,10,11,12)
                                
shift() and unshift()
    ●   shift() is like pushing new first values, unshift() 
        is like popping the first value.  These operations 
        are done on the leftmost end of the array.
    ●   @stk = (5..9);
        shift(@stk, 4);   # now (4..9)
        shift @stk, (1..3); # now (1..9)
        $a = unshift @stk;
        # remove 1 leaving (2..9), $a = 1

                                 
foreach Control Structure
    ●   Syntax: foreach $var (@arr) { body; }
    ●   Example: form the pural form of each fruit:
        @fruits = qw/mango banana durian/;
        foreach $fr (@fruits) {
          $fr .= 's';
        }
        print “@fruitsn”;



                              
Perl's Default Variable: $_
    ●   If you omit $var in a foreach loop, you can refer 
        to this variable using $_
        foreach (1..10) {
          $sum += $_;
        }
        print “Total of 1..10 is $sumn”;
    ●   If you omit $var in a print statement, the value of 
        $_ will be printed.
        $_ = “Today is Saturdayn”;
        print;
                                 
reverse() and sort()
    ●   reverse(@arr) reverses the order of values in 
        the list
        @fruits = qw/mango papaya chico/;
        @revfr = reverse(@fruits);
        @fruits = reverse(@fruits);
    ●   sort(@arr) sorts the values in the list in 
        increasing lexicographic order, or string order, 
        not numeric order
        @fruits = qw/mango papaya chico/;
        @sfruits = sort(@fruits);
        @rfruits = reverse sort @fruits;
                                
Forcing scalar() Context
    ●   If you want to use an array @arr in a scalar 
        context (for example, get the number of 
        elements in the list), use the function scalar()
        @fruits = qw/mango banana orange/;
        print “Favorite fruits: @fruitsn“;
        print “My favorite fruits are “, 
        scalar(@fruits), “ in alln”;



                               
<STDIN> as List or Scalar
    ●   $line = <STDIN>;
        reads one line from <STDIN>
    ●   @lines = <STDIN>;
        reads the entire file <STDIN> until end­of­file 
        and assigns each line as an element of the 
        array @lines. If file is big, @lines may use up a 
        huge amount of memory. The end­of­file of 
        <STDIN> is indicated by typing Control­D in 
        Unix.
                                
Sorting Lines from <STDIN>
    ●   chomp(@lines = <STDIN>);
        @lines = sort @lines;
        foreach $line (@lines) {
           print “$linen”;
        }
        print “**No more**”;




                            
Exercises
    ●   Write a program that reads from <STDIN> a set 
        of numeric values, one per line, and computes 
        the mean and variance of these values. If N is 
        the number of values, then
        mean = (sum of all values) / N;
        variance = 
          (sum square(each value – mean)) / N;
    ●   Write a program that reads lines from <STDIN>, 
        sorts these lines in reverse alphabetical order, 
        prints the lines, and prints the total number of 
 
        lines.                    
Hashes
    ●   A hash is a list of key­value pairs. The variable 
        name starts with %
        %age = (“Pablo”, 62, “Karen”, 23, 
        “Paul”, 33);
        Here the key “Pablo” has value 62, the key 
        “Karen” has value 23, and the key “Paul” has 
        value 33.
    ●   Accessing a hash by key
        $age{“Paul”}  gives 33
        $age{“Karen”} gives 23
                                 
Hashes: Big Arrow Notation
    ●   %lname = (“Pablo”=>”Manalastas”,
        “Rojo”=>”Sanchez”,
        “Joy”=>”Fernando”);
    ●   %month = (1=>”January”, 
        2=>”February”,
        3=>”March”, 4=>”April”, 5=>”May”);
    ●   $lname{“Rojo”} gives “Sanchez”
        $month{4} gives “April”

                            
Using a Hash
    ●   %lname = (“Pablo”=>”Manalastas”,
        “Rojo”=>”Sanchez”,
        “Joy”=>”Fernando”);
        print “Enter first name: “;
        chomp($fname = <STDIN>);
        print “Last name of $fname is “,
          $lname{$fname}, “n”;




                         
Keys & Values
    ●   %month = (1=>”January”, 
        2=>”February”,
        3=>”March”, 4=>”April”, 5=>”May”);
    ●   @k = keys %month;
        # @k is the array of keys only
    ●   @v = values %month;
        # @v is the array of values only




                                
each() & exists()
    ●   %month = (1=>”January”, 
        2=>”February”,
        3=>”March”, 4=>”April”, 5=>”May”);
    ●   To access each (key,value) pair: 
        while(($key,$val) = each %month) {
          print “$key => $valn”;
        }
    ●   To check if a value exists for a key
        If( exists $month{13}) {
          print “That is $month{13}n”;
 
        }                        
Hash Element Interpolation
    ●   %month = (1=>”January”, 
        2=>”February”,
        3=>”March”, 4=>”April”, 5=>”May”);
    ●   Can interpolate each element
        print “First month is $month{1}n”;
    ●   Not allowed
        print “The months are: %monthn”;



                         
Exercises
    ●   Write a program that reads a series of words 
        (with one word per line) until end­of­input, then 
        prints a summary of how many times each word 
        was seen.
    ●   Write a program that prompts for month number 
        (1­12), day number (1­31), and year (1900­
        2008), and display the inputs in the form
        “MonthName  day, year” (without the quotes).

                                
Subroutines
    ●   User­defined functions that allow the 
        programmer to reuse the same code many 
        times in his program
    ●   Subroutine name starts with &, in general
    ●   Defining a subroutine
        sub subName {
          subBody;
        }

                                 
Example Function
    ●   Defining a function:

        sub greet {
          print “Hello!n”;
        }
    ●   Using the function:

        &greet;

                                
Passing Arguments
    ●   If the subroutine invocation is followed by a list within 
        parenthesis, the list is assigned to special variable @_ 
        within the function
    ●   Example
        &greet(“Pablo”, “Jose”, “Maria”);

        You can use the arguments as follows:
        sub greet {
          for each $name in (@_) {
            print “Hello $name!n”:
          }
        } 
                                    
Local Variables; Returning Values
    ●   sub sum {
          local($total);
          $total = 0;
          for each $num in (@_) {
            $total += $num;
          }
          $total;
        }


                               
Exercises
    ●   Write a function that returns the product of its 
        arguments
    ●   Write a function that accepts two arguments n 
        and d, returns a list of two numbers q and r, 
        where q is the quotient of n and d, and r is their 
        remainder
    ●   Write a function that, given any number n as 
        argument, prints the value of that number in 
        words, as in a checkwriter.
                                 

More Related Content

What's hot (12)

Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
Basic perl programming
Basic perl programmingBasic perl programming
Basic perl programming
 
Perl intro
Perl introPerl intro
Perl intro
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Syntax
SyntaxSyntax
Syntax
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
Scripting3
Scripting3Scripting3
Scripting3
 
Introduction in php
Introduction in phpIntroduction in php
Introduction in php
 
Object Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHPObject Calisthenics Adapted for PHP
Object Calisthenics Adapted for PHP
 

Similar to perl_lessons (20)

tutorial7
tutorial7tutorial7
tutorial7
 
Lecture 23
Lecture 23Lecture 23
Lecture 23
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
Introduction to perl_control structures
Introduction to perl_control structuresIntroduction to perl_control structures
Introduction to perl_control structures
 
PERL for QA - Important Commands and applications
PERL for QA - Important Commands and applicationsPERL for QA - Important Commands and applications
PERL for QA - Important Commands and applications
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Introduction to perl_lists
Introduction to perl_listsIntroduction to perl_lists
Introduction to perl_lists
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Cs3430 lecture 16
Cs3430 lecture 16Cs3430 lecture 16
Cs3430 lecture 16
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
Php functions
Php functionsPhp functions
Php functions
 

More from tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

More from tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Recently uploaded

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
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
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
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
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
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
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 

Recently uploaded (20)

Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
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...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
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
 
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
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 

perl_lessons

  • 1. Perl Tutorial Pablo Manalastas <pmanalastas@ateneo.edu>  LEARNING PERL    
  • 2. Numbers ● Numbers are double precision floating point  values (double in C) 3,  1.5,  2.7e8,  2_427_132_115, 0577, 0xf3ab, 0b1110001011 ● Numeric operations Add (+), subtract (­), negate (­), multiply (*),  divide (/), modulus (%) 3 + 4.2,   2.3e4*6.2523,  10%4    
  • 3. Strings ● Can be any length & can contain any characters ● Single­quoted strings 'Pablo de Gracia, Jr.' 'The winter of our discontent.' 'Queen's Jewels' # the single quote ' is specified as ' 'The backslash  is special' # the backslash  is specified as     
  • 4. Strings ● Double­quoted strings ”against earth's flowing breast” “I am called ”handsome” by some” “I came.nI saw.nI conquered.n” “Tabtseparatedtentriesthere” ● String concatenation “Hello ”  .  “worldn” ● String repetition “maganda ” x 3    
  • 5. Autoconversion: Numbers & Strings ● Arithmetic operations (+,­,*,/,%) convert strings  to numbers “12plus2” + “3”   # gives the number 15 ● String operation (.) converts numbers to strings “XJW” . 24*5  # gives the string “XJW120”    
  • 6. Variables ● Variable names [$@%][A­Za­z_][0­9A­Za­z_]* ● Scalar variables, name starts with $ – Holds one value (scalar value) – Examples: $daily_rate = 350.00; $horse_name = “Heaven's Pride”; $monthly_pay = $daily_rate * 22;    
  • 7. Binary Assignment Operators ● Replace $var = $var op $val; by $var op= $val; ● Examples: $new_rate += 12; $quotient /= 10; $name .= “, PhD”; $balance ­= $withdrawal;    
  • 8. Output Using “print” ● Write output to stdout using print print “Hello, world!n”; print “The answer is ” . 350 * 6 .  “n”; print “The answer is ”, 350 * 6, “n”;    
  • 9. Interpolation ● Interpolation: the replacement of a scalar  variable by its value in a double quoted string or  when occuring alone ● Examples $meal = 'beef steak'; print “Juan ate $mealn”; print “I like $meal for dinnern”; print “Juan's dinner is “ . $meal; print “Juan's dinner is “, $meal;    
  • 10. Delimiting the Variable Name ● Use { } to delimit the variable name to be  interpolated ● Examples $what = 'steak'; print “I love all kinds of ${what}sn”; print “I love all kinds of $what”, “sn”; print “Prime rib is the $what of ${what}sn”;    
  • 11. Comparison Operators ● Numeric comparison operators ==, !=, <, >, <=, >= Examples: 50 == 100/2; # true 100/3 != 33.3 # true ● String comparison operators eq, ne, lt, gt, le, ge 'pedro' lt 'jose' # false 'jose' eq “jose” # true   ' ' gt '' # true  
  • 12. Boolean Values ● undef, number zero (0), string zero ('0'), the  empty string (''), are all false. Undef designates  a variable with no value assigned yet. ● non­zero numbers (like 1) and non­empty  strings (except '0') are all true.  ● Examples $bool1 = 'Fred' lt 'fred'; $bool2 = 'fred' lt 'Fred'; print $bool1;   # prints 1 for true print $bool2;   # empty string for false    
  • 13. If Control Structure ● Syntax if( condition ) { true­part; } else { false­part; } ● Example $disc = $b*$b – 4.0*$a*$c; if( $disc >= 0.0 ) {   print “Real rootsn”; } else {   print “Complex rootsn”; }    
  • 14. Reading One Line from Stdin ● Use <STDIN> to read one line from standard  input, usually the console keyboard ● Examples: print “Enter first name: “; $fname = <STDIN>; print “Enter last name: “; $lname = <STDIN>; chomp($fname); chomp($lname); print “Your name: $fname $lnamen”;    
  • 15. The chomp() Function ● chomp() removes a trailing newline 'n' from the  string value of a variable ● Version2 of program: print “Enter first name: “; chomp($fname = <STDIN>); print “Enter last name: “; chomp($lname = <STDIN>); print “Your name: $fname $lnamen”;    
  • 16. While Control Structure ● Syntax: initialization; while ( condition ) {    statements;    reinitialization; } ● Example: $i = 1; while($i <= 10) {   print “Counting $in”;   ++$i; }    
  • 17. UNDEF ● If an undefined variable is used as a number,  undef is like zero (0). If used as a string, undef  is like the empty string ('') ● If $x is undefined, the following are allowed: $x += 2; $x .= 'bye'; ● If $x has a value, then $x = undef; makes $x undefined    
  • 18. The defined() Function ● The <STDIN> operation may return the value  undef when there is no more input, such as at  end­of­file ● The function defined() can test if <STDIN> read  one line of input from standard input. ● Example while(defined($line = <STDIN>)) {   print “You typed: $line”; } print “No more inputn”;    
  • 19. Exercises ● Write a Perl program that reads lines of input  from <STDIN>, and prints each line read. Stop  when the line that is read is 'Done' (without the  quotes). ● Write a Perl program that reads the values of  three variables $num1, $oper, and $num2 from  <STDIN>.  If the value of $oper is one of the  strings 'plus', 'minus', 'times', or 'over', the  program should carry out the indicated  operation on $num1 and $num2.    
  • 20. Lists & Arrays  ● List: an ordered collection of scalar values. The  index is the position of a scalar value in the list.  The index runs from 0 to (n­1), where n is the  size of the list. An array is a variable that  contains a list, and starts with a @sign ● Example: @quals @friends    
  • 21. Initializing Arrays with Literal Values ● An array may be initialized with values in  parentheses ( ). Example:  @propty = ('Pablo', 62, 'male',  undef); Here, the array is @propty, and the values in  the list are: $propty[0] is 'Pablo' $propty[1] is 62 $propty[2] is 'male' $propty[3] is undef  #civil status    
  • 22. Values May All Be Same Type ● All list values may be the same type @friends = ('Pablo', 'Jose',  'Juan', 'Mario', 'David'); Here, the array is @friends, and the values in  the list are: $friends[0] is 'Pablo' $friends[1] is 'Jose' $friends[2] is 'Juan' $friends[3] is 'Mario' $friends[4] is 'David'    
  • 23. Values of Array Indices ● Any value, variable, or expression, whose value is  integer or can be converted to integer can be used as  index. ● Example: $ndx = 2.5; $friends[$ndx+1] is $friends[3] ● $#friends is the value of the last index of array  @friends, which is 4. ● $friends[$#friends+10] = 'Carlos'; adds element 'Carlos' at index 14, the 15th element.  Values at index 5 to 13 will be undef.    
  • 24. Initializing Array with Literal Values ● @arr = ( ); @arr = (5..10, 17, 21); @arr = ($a..$b); @arr = qw/  Pablo Jose Mario /; @arr = qw! Pablo Jose Mario !; @arr = qw( Pablo Jose Mario ); @arr = qw{ Pablo Jose Mario }; @arr = qw< Pablo Jose Mario >;    
  • 25. Interpolate Arrays/Values in Strings ● If @arr is an array, then array @arr and list  value $arr[k] will be interpolated (evaluated)  when placed inside double quoted strings ● Example interpolating arrays @arr = (5..7); print “Four @arr eightn”; # will print Four 5 6 7 eight ● Example interpolating list values @toy = ('toycar', 'toyrobot',  'toygun');   print “I have a $toy[2] at homen”;  
  • 26. pop( ) Function ● pop() removes the rightmost list value from an  array ● Example: @stk = (5..9); $a = pop(@stk); # remove 9 leaving 5..8, $a = 9 $b = pop @stk; # remove 8 leaving 5..7, $b = 8 pop @stk;    # remove 7 leaving 5..6    
  • 27. push() Function ● push(): adds new rightmost values to the list of  an array ● Example: @stk = (5..8); push(@stk, 0);  # now (5,6,7,8,0) push @stk, (1..3);# now (5,6,7,8,0,1,2,3) @stk2 = qw/ 10 11 12 /; push @stk, @stk2;  # now (5,6,7,8,0,1,2,3,10,11,12)    
  • 28. shift() and unshift() ● shift() is like pushing new first values, unshift()  is like popping the first value.  These operations  are done on the leftmost end of the array. ● @stk = (5..9); shift(@stk, 4);   # now (4..9) shift @stk, (1..3); # now (1..9) $a = unshift @stk; # remove 1 leaving (2..9), $a = 1    
  • 29. foreach Control Structure ● Syntax: foreach $var (@arr) { body; } ● Example: form the pural form of each fruit: @fruits = qw/mango banana durian/; foreach $fr (@fruits) {   $fr .= 's'; } print “@fruitsn”;    
  • 30. Perl's Default Variable: $_ ● If you omit $var in a foreach loop, you can refer  to this variable using $_ foreach (1..10) {   $sum += $_; } print “Total of 1..10 is $sumn”; ● If you omit $var in a print statement, the value of  $_ will be printed. $_ = “Today is Saturdayn”; print;    
  • 31. reverse() and sort() ● reverse(@arr) reverses the order of values in  the list @fruits = qw/mango papaya chico/; @revfr = reverse(@fruits); @fruits = reverse(@fruits); ● sort(@arr) sorts the values in the list in  increasing lexicographic order, or string order,  not numeric order @fruits = qw/mango papaya chico/; @sfruits = sort(@fruits); @rfruits = reverse sort @fruits;    
  • 32. Forcing scalar() Context ● If you want to use an array @arr in a scalar  context (for example, get the number of  elements in the list), use the function scalar() @fruits = qw/mango banana orange/; print “Favorite fruits: @fruitsn“; print “My favorite fruits are “,  scalar(@fruits), “ in alln”;    
  • 33. <STDIN> as List or Scalar ● $line = <STDIN>; reads one line from <STDIN> ● @lines = <STDIN>; reads the entire file <STDIN> until end­of­file  and assigns each line as an element of the  array @lines. If file is big, @lines may use up a  huge amount of memory. The end­of­file of  <STDIN> is indicated by typing Control­D in  Unix.    
  • 34. Sorting Lines from <STDIN> ● chomp(@lines = <STDIN>); @lines = sort @lines; foreach $line (@lines) {    print “$linen”; } print “**No more**”;    
  • 35. Exercises ● Write a program that reads from <STDIN> a set  of numeric values, one per line, and computes  the mean and variance of these values. If N is  the number of values, then mean = (sum of all values) / N; variance =    (sum square(each value – mean)) / N; ● Write a program that reads lines from <STDIN>,  sorts these lines in reverse alphabetical order,  prints the lines, and prints the total number of    lines.  
  • 36. Hashes ● A hash is a list of key­value pairs. The variable  name starts with % %age = (“Pablo”, 62, “Karen”, 23,  “Paul”, 33); Here the key “Pablo” has value 62, the key  “Karen” has value 23, and the key “Paul” has  value 33. ● Accessing a hash by key $age{“Paul”}  gives 33 $age{“Karen”} gives 23    
  • 37. Hashes: Big Arrow Notation ● %lname = (“Pablo”=>”Manalastas”, “Rojo”=>”Sanchez”, “Joy”=>”Fernando”); ● %month = (1=>”January”,  2=>”February”, 3=>”March”, 4=>”April”, 5=>”May”); ● $lname{“Rojo”} gives “Sanchez” $month{4} gives “April”    
  • 38. Using a Hash ● %lname = (“Pablo”=>”Manalastas”, “Rojo”=>”Sanchez”, “Joy”=>”Fernando”); print “Enter first name: “; chomp($fname = <STDIN>); print “Last name of $fname is “,   $lname{$fname}, “n”;    
  • 39. Keys & Values ● %month = (1=>”January”,  2=>”February”, 3=>”March”, 4=>”April”, 5=>”May”); ● @k = keys %month; # @k is the array of keys only ● @v = values %month; # @v is the array of values only    
  • 40. each() & exists() ● %month = (1=>”January”,  2=>”February”, 3=>”March”, 4=>”April”, 5=>”May”); ● To access each (key,value) pair:  while(($key,$val) = each %month) {   print “$key => $valn”; } ● To check if a value exists for a key If( exists $month{13}) {   print “That is $month{13}n”;   }  
  • 41. Hash Element Interpolation ● %month = (1=>”January”,  2=>”February”, 3=>”March”, 4=>”April”, 5=>”May”); ● Can interpolate each element print “First month is $month{1}n”; ● Not allowed print “The months are: %monthn”;    
  • 42. Exercises ● Write a program that reads a series of words  (with one word per line) until end­of­input, then  prints a summary of how many times each word  was seen. ● Write a program that prompts for month number  (1­12), day number (1­31), and year (1900­ 2008), and display the inputs in the form “MonthName  day, year” (without the quotes).    
  • 43. Subroutines ● User­defined functions that allow the  programmer to reuse the same code many  times in his program ● Subroutine name starts with &, in general ● Defining a subroutine sub subName {   subBody; }    
  • 44. Example Function ● Defining a function: sub greet {   print “Hello!n”; } ● Using the function: &greet;    
  • 45. Passing Arguments ● If the subroutine invocation is followed by a list within  parenthesis, the list is assigned to special variable @_  within the function ● Example &greet(“Pablo”, “Jose”, “Maria”); You can use the arguments as follows: sub greet {   for each $name in (@_) {     print “Hello $name!n”:   } }     
  • 46. Local Variables; Returning Values ● sub sum {   local($total);   $total = 0;   for each $num in (@_) {     $total += $num;   }   $total; }    
  • 47. Exercises ● Write a function that returns the product of its  arguments ● Write a function that accepts two arguments n  and d, returns a list of two numbers q and r,  where q is the quotient of n and d, and r is their  remainder ● Write a function that, given any number n as  argument, prints the value of that number in  words, as in a checkwriter.