SlideShare a Scribd company logo
Programming on the Web(CSC309F)


          Tutorial 7: Perl
       TA:Wael Abouelsaadat
  WebSite:   http://www.cs.toronto.edu/~wael

   Office-Hour: Friday 12:00-1:00 (SF2110)

        Email: wael@cs.toronto.edu




                                               1
Introduction to Perl
Ø History of Perl!
     Ø Initially developed by Larry Wall (English major student then!) in 1987.
     Ø Modules continuously added since version 2.0
     Ø Latest version is Perl 5.6.1
     Ø Ported to 83 platforms.
     Ø Most popular “scripting” language for server-side web development.


Ø Pros && Cons:
     ü Powerful in manipulating textual data.
     ü A very rich set of pattern-matching operations (used extensively in text-searching, NLP systems,…).
     ü Rich set of functions (via Perl modules).
     ü Allow you to get the job done very quickly (but not necessarily elegantly! ).
     û No GUI library.
     û Weird syntax (greatly reduces maintainability of Perl progra ms).
     Í Perl is an interpreted language.
     Í Unix influence (originally built as a replacement for shell scripts and awk).



Ø helloworld.pl
     § Source:
           print ( “Hello to Perl World!” );
           print “Hello to Perl World!”;        # yes, no brackets!
     § Run it:
           C:> perl helloworld.pl
            Hello to Perl World!Hello to Perl World!




                                                                                                             2
Perl – Data types
Ø Specifying Types and Containers:
          § Variables are not explicitly declared. Perl interpreter guesses the type from the way the variable is written.
                        $var - names a variable that holds a scalar data type (integer, floating point or string).
                        @var - names a variable that holds an array of scalars, or list.
                        %var - names a variable that holds an associative array of scalars.
                        &var - names a subroutine.
          § E.g.
                        #Defining a scalar
                        $Name = "Jack";
                        $Age = 10;

                        #Defining and handling an array
                        @Colors      = ("Red","Pink","Yellow");
                        $FirstColor = $Colors[0];
                        print( $FirstColor );                 # Outputs Red
                        $Colors[0] = "White";
                        print( $Colors[0] );                  # Outputs White
                        $Colors[100] = “Blue”;                # This is valid because Arrays in Perl are dynamic in size
                        print( $Colors[100] );               # Outputs Blue
                        print( $#Colors );                    # Prints 100 which is the last index of the array. This is a unique variable
                                                              # defined by the perl interpreter to give you access to current size of array

                        # Defining and handling a hash table
                        %Address = ("Apartment" => 101,
                                        "Street"     => "Bloor",
                                        "City"       => "Toronto");
                        $streetName = $Address{"Street"};
                        print( $streetName );                   # Outputs Bloor
                        $Address{"City"} = "Ottawa";
                        print( $Address{"City"} );             # Outputs Ottawa
                        delete $Address{"City"};
                        @tkeys = keys(%Address);               # keys function returns an array of the keys in the hash table
Ø Global vs. Local variables:                                                                                                   3
          § $Name    = “John”;          # Visible in the whole program
            my $Name = “John”;          # Visible in the block it is declared in
Perl – Strings
Ø Strings:

     § Difference between using the single quote (') and the double quote (") to delimit strings:
                          $Client = 'John Luu';
                          @Items = ( "Chocolate", "Biscuits", "Milk");
                          $Total = 60;
                          $Transaction = "$Client is buying @Items for $ $Total";
                          print( $Transaction );           # Outputs John Luu is buy ing Chocolate Biscuits Milk for $ 60

     § Concatenating Strings:
                           $FirstName = ‘John';      $LastName = “Black”;
                           $FullName = $First Name . $LastName ;    # FullName is now “John Black”

     § String operators:
                           # lt: less than , le: less or equal , eq: equal , ge: greater or equal , ne: not equal , eq: equal
                           $Val1 = ‘1.1’;                   $Val2 = ‘1.0’;
                           $Val3 = ‘bbb’;                   $Val4 = ‘aaa’;
                           if( ($Val1 gt $Val2) && ($Val3 lt $Val4 ) ) ……………………

     § Pattern matching:
                           # =~:  does match , !~: does not match
                           $CatString = “tomcat”
                           if ( $CatString =~ /cat/ ) …. # Right-hand-side of these operators must always be a regular expression




                                                                                                                                4
Perl – Control , Loops and Functions
ØControl statements:
         § If statement:                                                             Unless Statement
                        if( $Size < 10.0 ) {                                         unless( $Name eq “John Black” ){
                              print( "Length is too small!n" );                            print( “ You are not John Black” );
                         }                                                           }
                         elsif ( $Size > 100.0 ) {
                             print( "Length is too big!n" );
                         }
                         else{
                              print( "Length is just right!n" );
                          }
Ø Looping:
         § While Loops:                                                                    For Loops:
                       while( $n <= 10 ) {                                                  for( $n = 1; $n <= 10; ++$n ) {
                          printf( "%d squared is %dn", $n, $n*$n );                           printf( "%d squared is %dn", $n, $n*$n );
                           $n = $n + 1;                                                      }
                        }
         § For-each Loops:
                      @Digits = (0,1,2,3,4,5,6,7,8,9);
                      foreach $n (@Digits) {
                           printf( "%d squared is %dn", $n, $n*$n );
                      }
Ø Functions
         § e.g.:
                        sub func1{
                          my($param1,$param2) = @_;                 # parameters are passed in an array called @_
                          print "Inside func";
                          $param1 * $param2;                        # same as return($param1 * $param2 );
                        }
                        print(" Before calling func1");
                        $result = func1( 10,20 );                                                                             5
                         print(" After calling func1");
                         print(" result : $result");                # prints result: 200
Perl – Functions cont’d
Ø Perl built-in functions:
     § Debugging Functions
                         # caller( )
                         # Unwinds the calling stack: ($package, $filename, $line,$SubName , $args,$$contentxt) = caller( $frame );
                         a( );
                         sub a { b(); }
                         sub b { c(); }
                         sub c { print ( “@{ [ caller(1) ] } “ ); }   # Outputs main script.pl 2 main::b 1 0

                            # die( )
                            # Kills a process at a given point.
                            open ( REPORT_FILE, ">report.txt" ) || die " Error opening report.txt $! n " ;
                            # The above translates to if( open( ….) continue ) else { die …. }

                            # warn( )
                            # Does the same thing as die but does not exit.
     § Time Functions
                            # ($secs , $min, $hr, $mday, $mnth, $yr, $wd, $yd, $ds ) = localtime ( ); Gets local time
                            # ($user, $system, $child_user, $child_system ) = times( );               Benchmark code
                            # sleep( $seconds );
     § Variable Functions
                            # sort(…) Sorts an array in alphabetical order, or by a user-defined function.
                            @DestArray = ( ‘Apples’, ‘Bananas’, ‘Carrots’ );
                            @NewArray = sort( @DestArray );                        #Be carefull with arrays of numbers

                            # split(…) Takes a scalar and separates it based on on the criteria us er provides
                            # @NewArray = split( $text, $ScalarName );         $text can be delimiter or regular expression
                            @splitArray = spli( “,” , $scalarName );

                            # grep(…) Finds which element in an array satisfies a condition.
                            #@NewArray = grep( EXPRESSION , @arrayToMatch );
                            @Foods = ( ‘turkey’, ‘lucky charms ’, ‘oranges’ );                                           6
                            @longFoods = grep( length($_) > 6 , @foods );
Perl – Functions cont’d
                      # map(…) Makes a new array based on a transform from the old array.
                      # @NewArray = map( &function, @source_array );
                      @NewArray = map( MyFunc ( $_ ) , @SourceArray );
§ File Functions
                      # $bytes = read( FILEHANDLE, $scalar, $length, $offset )
                      Open( FILEHANDLE, “file” );
                      $bytes = read( FILEHANDLE, $input, 40, 20 ); # reads 40 characters from file into $input starting at 20

                      #printf [FILEHANDLE] $format_string, @arrayOfValues;
                      use FileHandle;
                      my $Fhandle = new FileHandle( “> my_file” );
                      $longvarb    = “This has 23 chars in it”;
                      printf $Fhandle “%10.10sn” , $longvarb;
§String Functions
                      #chop( )    Deletes the last character in a scalar. If applied to Array, hash => does the same!
                      $line = “ Please chop the letter T”;
                      chop( $line );

                      # chomp( ) Deletes the new line character, at the end of the line, if exists.
                      # More funs: chr, crypt, hex, index, lc, length, oct, ord, pack, reverse, rindex, sprintf, substr, uc, ucfirst
§ Array Functions
                      #pop, push, shift, splice, unshift
§ Hash Functions
                      # delete, each, exists, keys, values
§ I/O Functions
                      # binmode , close, closedir, dbmclose, dbmopen, eof, fileno, flock, format, getc, print, printf, read, readdir,
                      # rewinddir, seek, seekdir, select, syscall, sysread, sysseek, syswrite, tell, telldir, truncate, write
§ Files/Directories Functions
                      # -X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename,
                      # rmdir, stat, symlink, umask, unlink, utime

                                                                                                                           7
Perl – Input and Output

Ø Printing Output:
    § Standard Output:
                         print( STDOUT "Hello World!n" );
                         print( "Hello World! n" );
    § Files:
                         open( OUT, ">test.dat" );                   # Associates file handle with file
                         print( OUT “ This text will be written in the file " );



ØReading input:
    § Standard Output:
                         $NewLine = <STDIN>;                         # Reads one complete line from standard input
                         $ProgramArguments = <ARGV>;                 # Refer to arguments on the command line.
                                                                     # e.g. perl prog param1 param2 param3
    § Files:
                         open( IN, “<test.dat" );                    # Associates file handle with file
                         $Line = <IN>;                               # Reads the first line
                         close( IN );




                                                                                                                     8
Perl – Program Structure
Ø Perl Files (.pl) vs Perl Modules (.pm)
                                                                                            File.pl        File.pm
     § Where is main()?
ØRequire Statement                                                                                func1
     § Causes the Perl interpreter to “execute” the code in the require d file!
                           # foo.pl
                                                                                                  func2
                           perl code
                           more perl code….
                                                                                               some code
                           1;
                           #-----------------------------------------------
                           # Poo.pl
                           require “foo.pl”;
                           perl code                   # you can call functions in foo.pl
Ø Defining a Perl package and the use statement
     § Semi-Object Oriented Programming! Creates a namespace.
                         # Student.pm
                         #!/usr/sbin/perl
                         package Student;
                         sub new {
                             # Initialization code
                         }
                         sub printDetails{
                             # perl code …..
                         }
                         #-------------------------------
                         # foo.pl
                         use Student;                     # Like inc lude in C++
                         $new_student = new Student( );
                         $new_student->printDetails( );
Ø Another way to use use !
                            Use CGI qw();                     # Uses a specific function in a module: qw             9
Ø use strict;
     § Forces Perl interpreter to be strict in using types. Will save you a lot of time !
Perl - CGI
Ø Handling Query String
         # dispatcher.pl
         use strict;
         # Retrieving query string
         $request_method = $ENV{‘REQUEST_METHOD’};
         if( $request_method eq “GET” ){
                  $query_string = $ENV{‘QUERY_STRING’};
         }
         elsif ( $request_method eq “POST” ){
                  read( STDIN , $query_string, $ENV{‘CONTENT_LENGTH’} );
         }
         else{
                  print(“Invalid Request Method !”);
                 exit( 1 );
         }
         # Extracting name -value pairs from query string (param1=value1&param2=value2&..…)
         @name_value_paris = split( /&/, $query_string );
         foreach $name_value (@name_value_pairs){
             ($name, $value ) = split( /=/, $name_value );
             #more Perl code…..
         }


Ø Generating HTML
         print “Content-type: text/htmlnn”;
         print “<html><head> n”;
         print “<title> foo title </title></head> n”;
         print “<body>”
         ……………..
         Print “</body></html>

                                                                                              10
Perl - cgi.pm
Ø Using cgi.pm
         use strict;
         use CGI qw(:standard);

         print ( header( ) );
         print( start_html( “Anna Web Page” ) );       # <html><head><title>Anna Web Page</title></head><body>
         print( table( ….) );
         print( a(…) );                                # <a href=“”> xyz </a>
         print( radio_group(…..) );
         print( end_html( ) );                         # </body></html>




                                                                                                           11
Assignment 3

Ø What is it about?                                      Client(Web-Browser)   Server(HTTP Server)



                                                               HTML/                   Perl/
Ø What can you do right now?                                 JavaScript/               CGI/
     § HTML       (design and layout of the web pages)         Cookies                Cookies
     § JavaScript (validations)


                                                                               SMTP                  POP3
Ø What you need to learn?
     § Perl
     § Cookies
     § CGI                                                                     SMTP Server   POP3 Server




                                                                                                12

More Related Content

What's hot

DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
leo lapworth
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and Patterns
Henry Osborne
 
Smelling your code
Smelling your codeSmelling your code
Smelling your code
Raju Mazumder
 
Functional Pe(a)rls version 2
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2
osfameron
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
Pete McFarlane
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
Ahmed Swilam
 
Descobrindo a linguagem Perl
Descobrindo a linguagem PerlDescobrindo a linguagem Perl
Descobrindo a linguagem Perl
garux
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
AbhishekSharma2958
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
Vic Metcalfe
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
leo lapworth
 
PHP for Python Developers
PHP for Python DevelopersPHP for Python Developers
PHP for Python Developers
Carlos Vences
 
Oops in php
Oops in phpOops in php
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
anzhong70
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
juzihua1102
 

What's hot (15)

DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
PHP Strings and Patterns
PHP Strings and PatternsPHP Strings and Patterns
PHP Strings and Patterns
 
Smelling your code
Smelling your codeSmelling your code
Smelling your code
 
Functional Pe(a)rls version 2
Functional Pe(a)rls version 2Functional Pe(a)rls version 2
Functional Pe(a)rls version 2
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Descobrindo a linguagem Perl
Descobrindo a linguagem PerlDescobrindo a linguagem Perl
Descobrindo a linguagem Perl
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
PHP for Python Developers
PHP for Python DevelopersPHP for Python Developers
PHP for Python Developers
 
Oops in php
Oops in phpOops in php
Oops in php
 
第二讲 预备-Python基礎
第二讲 预备-Python基礎第二讲 预备-Python基礎
第二讲 预备-Python基礎
 
第二讲 Python基礎
第二讲 Python基礎第二讲 Python基礎
第二讲 Python基礎
 

Viewers also liked

Tutorial%20-%20Content%20Management%20System
Tutorial%20-%20Content%20Management%20SystemTutorial%20-%20Content%20Management%20System
Tutorial%20-%20Content%20Management%20Systemtutorialsruby
 
R31%20Strong%20A%20Web-based%20Comparative%20Genomics%20tutorial%20Microbiolo...
R31%20Strong%20A%20Web-based%20Comparative%20Genomics%20tutorial%20Microbiolo...R31%20Strong%20A%20Web-based%20Comparative%20Genomics%20tutorial%20Microbiolo...
R31%20Strong%20A%20Web-based%20Comparative%20Genomics%20tutorial%20Microbiolo...tutorialsruby
 
T11_effects_of_peripheral_stim
T11_effects_of_peripheral_stimT11_effects_of_peripheral_stim
T11_effects_of_peripheral_stimtutorialsruby
 

Viewers also liked (8)

Tesi_Adamou
Tesi_AdamouTesi_Adamou
Tesi_Adamou
 
Tutorial%20-%20Content%20Management%20System
Tutorial%20-%20Content%20Management%20SystemTutorial%20-%20Content%20Management%20System
Tutorial%20-%20Content%20Management%20System
 
manual
manualmanual
manual
 
web20
web20web20
web20
 
R31%20Strong%20A%20Web-based%20Comparative%20Genomics%20tutorial%20Microbiolo...
R31%20Strong%20A%20Web-based%20Comparative%20Genomics%20tutorial%20Microbiolo...R31%20Strong%20A%20Web-based%20Comparative%20Genomics%20tutorial%20Microbiolo...
R31%20Strong%20A%20Web-based%20Comparative%20Genomics%20tutorial%20Microbiolo...
 
Lab_2_2009
Lab_2_2009Lab_2_2009
Lab_2_2009
 
TPR4
TPR4TPR4
TPR4
 
T11_effects_of_peripheral_stim
T11_effects_of_peripheral_stimT11_effects_of_peripheral_stim
T11_effects_of_peripheral_stim
 

Similar to tutorial7

Lecture 22
Lecture 22Lecture 22
Lecture 22rhshriva
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
NBACriteria2SICET
 
Scripting3
Scripting3Scripting3
Scripting3Nao Dara
 
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
 
Basic perl programming
Basic perl programmingBasic perl programming
Basic perl programming
Thang Nguyen
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
Sanketkumar Biswas
 
Data Types Master
Data Types MasterData Types Master
Data Types Master
Paolo Marcatili
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
Varadharajan Mukundan
 
Crash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmersCrash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmersGil Megidish
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl coursepartiernlow
 
Perl bhargav
Perl bhargavPerl bhargav
Perl bhargav
Bhargav Reddy
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 

Similar to tutorial7 (20)

Lecture19-20
Lecture19-20Lecture19-20
Lecture19-20
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
perl_lessons
perl_lessonsperl_lessons
perl_lessons
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Scripting3
Scripting3Scripting3
Scripting3
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
perl-pocket
perl-pocketperl-pocket
perl-pocket
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Basic perl programming
Basic perl programmingBasic perl programming
Basic perl programming
 
PHP and MySQL
PHP and MySQLPHP and MySQL
PHP and MySQL
 
Data Types Master
Data Types MasterData Types Master
Data Types Master
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
Crash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmersCrash Course in Perl – Perl tutorial for C programmers
Crash Course in Perl – Perl tutorial for C programmers
 
Perl courseparti
Perl coursepartiPerl courseparti
Perl courseparti
 
Perl bhargav
Perl bhargavPerl bhargav
Perl bhargav
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Lecture4
Lecture4Lecture4
Lecture4
 

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

Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 

Recently uploaded (20)

Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 

tutorial7

  • 1. Programming on the Web(CSC309F) Tutorial 7: Perl TA:Wael Abouelsaadat WebSite: http://www.cs.toronto.edu/~wael Office-Hour: Friday 12:00-1:00 (SF2110) Email: wael@cs.toronto.edu 1
  • 2. Introduction to Perl Ø History of Perl! Ø Initially developed by Larry Wall (English major student then!) in 1987. Ø Modules continuously added since version 2.0 Ø Latest version is Perl 5.6.1 Ø Ported to 83 platforms. Ø Most popular “scripting” language for server-side web development. Ø Pros && Cons: ü Powerful in manipulating textual data. ü A very rich set of pattern-matching operations (used extensively in text-searching, NLP systems,…). ü Rich set of functions (via Perl modules). ü Allow you to get the job done very quickly (but not necessarily elegantly! ). û No GUI library. û Weird syntax (greatly reduces maintainability of Perl progra ms). Í Perl is an interpreted language. Í Unix influence (originally built as a replacement for shell scripts and awk). Ø helloworld.pl § Source: print ( “Hello to Perl World!” ); print “Hello to Perl World!”; # yes, no brackets! § Run it: C:> perl helloworld.pl Hello to Perl World!Hello to Perl World! 2
  • 3. Perl – Data types Ø Specifying Types and Containers: § Variables are not explicitly declared. Perl interpreter guesses the type from the way the variable is written. $var - names a variable that holds a scalar data type (integer, floating point or string). @var - names a variable that holds an array of scalars, or list. %var - names a variable that holds an associative array of scalars. &var - names a subroutine. § E.g. #Defining a scalar $Name = "Jack"; $Age = 10; #Defining and handling an array @Colors = ("Red","Pink","Yellow"); $FirstColor = $Colors[0]; print( $FirstColor ); # Outputs Red $Colors[0] = "White"; print( $Colors[0] ); # Outputs White $Colors[100] = “Blue”; # This is valid because Arrays in Perl are dynamic in size print( $Colors[100] ); # Outputs Blue print( $#Colors ); # Prints 100 which is the last index of the array. This is a unique variable # defined by the perl interpreter to give you access to current size of array # Defining and handling a hash table %Address = ("Apartment" => 101, "Street" => "Bloor", "City" => "Toronto"); $streetName = $Address{"Street"}; print( $streetName ); # Outputs Bloor $Address{"City"} = "Ottawa"; print( $Address{"City"} ); # Outputs Ottawa delete $Address{"City"}; @tkeys = keys(%Address); # keys function returns an array of the keys in the hash table Ø Global vs. Local variables: 3 § $Name = “John”; # Visible in the whole program my $Name = “John”; # Visible in the block it is declared in
  • 4. Perl – Strings Ø Strings: § Difference between using the single quote (') and the double quote (") to delimit strings: $Client = 'John Luu'; @Items = ( "Chocolate", "Biscuits", "Milk"); $Total = 60; $Transaction = "$Client is buying @Items for $ $Total"; print( $Transaction ); # Outputs John Luu is buy ing Chocolate Biscuits Milk for $ 60 § Concatenating Strings: $FirstName = ‘John'; $LastName = “Black”; $FullName = $First Name . $LastName ; # FullName is now “John Black” § String operators: # lt: less than , le: less or equal , eq: equal , ge: greater or equal , ne: not equal , eq: equal $Val1 = ‘1.1’; $Val2 = ‘1.0’; $Val3 = ‘bbb’; $Val4 = ‘aaa’; if( ($Val1 gt $Val2) && ($Val3 lt $Val4 ) ) …………………… § Pattern matching: # =~: does match , !~: does not match $CatString = “tomcat” if ( $CatString =~ /cat/ ) …. # Right-hand-side of these operators must always be a regular expression 4
  • 5. Perl – Control , Loops and Functions ØControl statements: § If statement: Unless Statement if( $Size < 10.0 ) { unless( $Name eq “John Black” ){ print( "Length is too small!n" ); print( “ You are not John Black” ); } } elsif ( $Size > 100.0 ) { print( "Length is too big!n" ); } else{ print( "Length is just right!n" ); } Ø Looping: § While Loops: For Loops: while( $n <= 10 ) { for( $n = 1; $n <= 10; ++$n ) { printf( "%d squared is %dn", $n, $n*$n ); printf( "%d squared is %dn", $n, $n*$n ); $n = $n + 1; } } § For-each Loops: @Digits = (0,1,2,3,4,5,6,7,8,9); foreach $n (@Digits) { printf( "%d squared is %dn", $n, $n*$n ); } Ø Functions § e.g.: sub func1{ my($param1,$param2) = @_; # parameters are passed in an array called @_ print "Inside func"; $param1 * $param2; # same as return($param1 * $param2 ); } print(" Before calling func1"); $result = func1( 10,20 ); 5 print(" After calling func1"); print(" result : $result"); # prints result: 200
  • 6. Perl – Functions cont’d Ø Perl built-in functions: § Debugging Functions # caller( ) # Unwinds the calling stack: ($package, $filename, $line,$SubName , $args,$$contentxt) = caller( $frame ); a( ); sub a { b(); } sub b { c(); } sub c { print ( “@{ [ caller(1) ] } “ ); } # Outputs main script.pl 2 main::b 1 0 # die( ) # Kills a process at a given point. open ( REPORT_FILE, ">report.txt" ) || die " Error opening report.txt $! n " ; # The above translates to if( open( ….) continue ) else { die …. } # warn( ) # Does the same thing as die but does not exit. § Time Functions # ($secs , $min, $hr, $mday, $mnth, $yr, $wd, $yd, $ds ) = localtime ( ); Gets local time # ($user, $system, $child_user, $child_system ) = times( ); Benchmark code # sleep( $seconds ); § Variable Functions # sort(…) Sorts an array in alphabetical order, or by a user-defined function. @DestArray = ( ‘Apples’, ‘Bananas’, ‘Carrots’ ); @NewArray = sort( @DestArray ); #Be carefull with arrays of numbers # split(…) Takes a scalar and separates it based on on the criteria us er provides # @NewArray = split( $text, $ScalarName ); $text can be delimiter or regular expression @splitArray = spli( “,” , $scalarName ); # grep(…) Finds which element in an array satisfies a condition. #@NewArray = grep( EXPRESSION , @arrayToMatch ); @Foods = ( ‘turkey’, ‘lucky charms ’, ‘oranges’ ); 6 @longFoods = grep( length($_) > 6 , @foods );
  • 7. Perl – Functions cont’d # map(…) Makes a new array based on a transform from the old array. # @NewArray = map( &function, @source_array ); @NewArray = map( MyFunc ( $_ ) , @SourceArray ); § File Functions # $bytes = read( FILEHANDLE, $scalar, $length, $offset ) Open( FILEHANDLE, “file” ); $bytes = read( FILEHANDLE, $input, 40, 20 ); # reads 40 characters from file into $input starting at 20 #printf [FILEHANDLE] $format_string, @arrayOfValues; use FileHandle; my $Fhandle = new FileHandle( “> my_file” ); $longvarb = “This has 23 chars in it”; printf $Fhandle “%10.10sn” , $longvarb; §String Functions #chop( ) Deletes the last character in a scalar. If applied to Array, hash => does the same! $line = “ Please chop the letter T”; chop( $line ); # chomp( ) Deletes the new line character, at the end of the line, if exists. # More funs: chr, crypt, hex, index, lc, length, oct, ord, pack, reverse, rindex, sprintf, substr, uc, ucfirst § Array Functions #pop, push, shift, splice, unshift § Hash Functions # delete, each, exists, keys, values § I/O Functions # binmode , close, closedir, dbmclose, dbmopen, eof, fileno, flock, format, getc, print, printf, read, readdir, # rewinddir, seek, seekdir, select, syscall, sysread, sysseek, syswrite, tell, telldir, truncate, write § Files/Directories Functions # -X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename, # rmdir, stat, symlink, umask, unlink, utime 7
  • 8. Perl – Input and Output Ø Printing Output: § Standard Output: print( STDOUT "Hello World!n" ); print( "Hello World! n" ); § Files: open( OUT, ">test.dat" ); # Associates file handle with file print( OUT “ This text will be written in the file " ); ØReading input: § Standard Output: $NewLine = <STDIN>; # Reads one complete line from standard input $ProgramArguments = <ARGV>; # Refer to arguments on the command line. # e.g. perl prog param1 param2 param3 § Files: open( IN, “<test.dat" ); # Associates file handle with file $Line = <IN>; # Reads the first line close( IN ); 8
  • 9. Perl – Program Structure Ø Perl Files (.pl) vs Perl Modules (.pm) File.pl File.pm § Where is main()? ØRequire Statement func1 § Causes the Perl interpreter to “execute” the code in the require d file! # foo.pl func2 perl code more perl code…. some code 1; #----------------------------------------------- # Poo.pl require “foo.pl”; perl code # you can call functions in foo.pl Ø Defining a Perl package and the use statement § Semi-Object Oriented Programming! Creates a namespace. # Student.pm #!/usr/sbin/perl package Student; sub new { # Initialization code } sub printDetails{ # perl code ….. } #------------------------------- # foo.pl use Student; # Like inc lude in C++ $new_student = new Student( ); $new_student->printDetails( ); Ø Another way to use use ! Use CGI qw(); # Uses a specific function in a module: qw 9 Ø use strict; § Forces Perl interpreter to be strict in using types. Will save you a lot of time !
  • 10. Perl - CGI Ø Handling Query String # dispatcher.pl use strict; # Retrieving query string $request_method = $ENV{‘REQUEST_METHOD’}; if( $request_method eq “GET” ){ $query_string = $ENV{‘QUERY_STRING’}; } elsif ( $request_method eq “POST” ){ read( STDIN , $query_string, $ENV{‘CONTENT_LENGTH’} ); } else{ print(“Invalid Request Method !”); exit( 1 ); } # Extracting name -value pairs from query string (param1=value1&param2=value2&..…) @name_value_paris = split( /&/, $query_string ); foreach $name_value (@name_value_pairs){ ($name, $value ) = split( /=/, $name_value ); #more Perl code….. } Ø Generating HTML print “Content-type: text/htmlnn”; print “<html><head> n”; print “<title> foo title </title></head> n”; print “<body>” …………….. Print “</body></html> 10
  • 11. Perl - cgi.pm Ø Using cgi.pm use strict; use CGI qw(:standard); print ( header( ) ); print( start_html( “Anna Web Page” ) ); # <html><head><title>Anna Web Page</title></head><body> print( table( ….) ); print( a(…) ); # <a href=“”> xyz </a> print( radio_group(…..) ); print( end_html( ) ); # </body></html> 11
  • 12. Assignment 3 Ø What is it about? Client(Web-Browser) Server(HTTP Server) HTML/ Perl/ Ø What can you do right now? JavaScript/ CGI/ § HTML (design and layout of the web pages) Cookies Cookies § JavaScript (validations) SMTP POP3 Ø What you need to learn? § Perl § Cookies § CGI SMTP Server POP3 Server 12