Docstoc

Perl_14_Objects and Modules

Document Sample
Perl_14_Objects and Modules Powered By Docstoc
					              Chapter 14 - Objects and Modules
        Outline
        14.1           Introduction
        14.2           Using a Class
        14.3           Creating a Simple Class
        14.4           Inheritance
        14.5           Overriding Methods
        14.6           Other Class Relationships: Multiple Inheritance,
                       Composition and Containment
        14.7           Base Class UNIVERSAL
        14.8           Encapsulation: Public vs. Private
        14.9           Closure Method
        14.10          Implicit Functions
        14.11          AUTOLOAD Function
        14.12          Tied Variables
        14.13          Internet and World Wide Web Resources




 2001 Prentice Hall, Inc. All rights reserved.
                                            14.1 Introduction

      • Object Oriented Programming
              – Everything in life is an object and can be described as one
      • Classes
              – Encapsulation of data and functions
              – Information hiding
                     • One class does not know how another class works
                     • Classes can still communicate with one another
                         – Interfaces
              – Data is called a class’s attributes
              – Functionality is called a class’s methods




 2001 Prentice Hall, Inc. All rights reserved.
                                          14.2 Using a Class

      • How to use a class
              – Make an instance of that class
                     • Create an object of that class type
                         – All objects are references
                     • The new constructor
              – Use the arrow operator to call the classes methods
                     • objectName -> methodName( arguments )




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                     Outline
2    # Fig. 14.1: fig14_01.pl
3    # Using the FileHandle module
                                                                                 fig14_01.pl
4
5    use warnings;
6    use strict;
7    use FileHandle;
                                                  Two new FileHandle
8
                                                  objects are created using
9 my $write = new FileHandle;
                                                  the new constructor
10 my $read        = new FileHandle;
11
12 $write->open( ">filehandle.txt" ) or
                                                        The files are opened using the
13      die( "Could not open write" );
                                                        FileHandle’s open method
14 $read->open( "input.txt" ) or
15      die( "Could not open read" );
16
17 $write->autoflush( 1 );
18                                                         Using the print method
19 my $i = 1;                                              of FileHandle
20
21 while ( my $line = $read->getline() ) {
22      $write->print( $i++, " $line" );




 2001 Prentice Hall, Inc. All rights reserved.
                                          14.2 Using a Class



               This is a sample file.
               With some lines for
               demonstration purposes.




        Fig. 14.2 Contents of input.txt.




               1 This is a sample file.
               2 With some lines for
               3 demonstration purposes.




        Fig. 14.3 Contents of filehandle.txt (after the program has executed).


 2001 Prentice Hall, Inc. All rights reserved.
                            14.3 Creating a Simple Class

      • Implementation
              – Details of a class
                     • How it is organized
                     • What data it uses
                     • What algorithms it uses
              – Can change as long as they still do the same basic things
                     • If so then client code need not be changed
              – The bless function
      • Get and Set methods
              – Used to retrieve or store data into attributes
              – Should have means of validating the data



 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                        Outline
 2   # Fig. 14.4: Date.pm
 3   # A simple Date class
 4                                                                                Date.pm
 5   package Date;
 6
 7   use strict;
 8   use warnings;
 9
10   sub new
11   {
12      my $date =          { the_year => 1000,
13                            the_month => 1,
                                                   The bless function
14                            the_day => 1, };
15                                                 receives a reference and
16       bless( $date );                           turns it into an object
17       return $date;
18   }                                            The new method then
19                                                returns the Date
20   sub year                                     object
21   {
22      my $self = shift();
23
24       $self->{ the_year } = shift() if ( @_ );          The year function can be used to
25
                                                           either set the value of the_year
26       return $self->{ the_year };
27   }
                                                           or else return the value to the user
28


 2001 Prentice Hall, Inc. All rights reserved.
29   sub month                                                                           Outline
30   {
31      my $self = shift();
32                                                                            Date.pm
33       $self->{ the_month } = shift() if ( @_ );        The month function can be used to
34                                                        either set the value of the_month
35       return $self->{ the_month };
                                                          or else return the value to the user
36   }
37
38   sub day
39   {
40      my $self = shift();
41
42       $self->{ the_day } = shift() if ( @_ );        The day function can be used to
43                                                      either set the value of the_day
44       return $self->{ the_day };
                                                        or else return the value to the user
45   }
46
47   sub setDate
48   {
49      if ( @_ == 4 ) {
50         my $self = shift();
51         $self->month( $_[ 0 ] );           The setDate method is used to set
52         $self->day( $_[ 1 ] );             all there values; day, month and year
53         $self->year( $_[ 2 ] );
54      }
55      else {
56         print( "Method setDate requires three arguments.\n" );
57      }
58   }
59
 2001 Prentice Hall, Inc. All rights reserved.
60 sub print                                                                            Outline
61 {                                              The print function is used
62      my $self = shift();                       to display the month, day       Date.pm
63      print( $self->month );                    and year in the proper format
64      print( "/" );
65      print( $self->day );
66      print( "/" );
67      print( $self->year );
68 }
69




 2001 Prentice Hall, Inc. All rights reserved.
1 #!/usr/bin/perl                                                                              Outline
2    # Fig. 14.5: fig14_05.pl
3    # Using class Date.                                                                fig14_05.pl
4
5    use Date;
6    use strict;
                                              The new function is called
7    use warnings;
                                              to create a new Date object
8
9    my $today = new Date;
10
11 $today->setDate( 7, 14, 2000 );                      Set the date by sending
12 print( $today->month() );                            three arguments
                                                       Uses the arrow operator to get
13 print( "\n" );                                      the value of the_month
14 $today->print();                                Call the print method
15 print( "\n" );                                  to display the entire date
7                                                                                       Program Output
7/14/2000




 2001 Prentice Hall, Inc. All rights reserved.
                                              14.4 Inheritance

      • Inheritance
              – Deriving a class
                     • Classes can be made based off of pre-existing classes
                     • They can use attributes and behaviors of the old class
              – Software reuse
              – The @ISA array
      • Composition
              – Objects of old classes can be data members




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                            Outline
2    # Fig. 14.6: Employee.pm
3    # Implementation of class Employee.
                                                                                       Employee.pm
4
5    package Employee;
6
7    use strict;
8    use warnings;
9    use Date;
10
11 sub new                                            The new function has to be made
12 {                                                  differently in order to account for the
13      my $type = shift();                           fact that a user may not want to make
14      my $class = ref( $type ) || $type;            a employee object every time.
15
16      my $hireDay = new Date;
17      my $self = {         firstName => undef,
18                           lastName => undef,
19                           hireDay => $hireDay };
20
                                                      The bless function makes a
21      bless( $self, $class );
                                                      new object of the right class
22      return $self;
                                                      and returns it to the user
23 }
24




 2001 Prentice Hall, Inc. All rights reserved.
25   sub firstName                                                                              Outline
26   {
27      my $self = shift();
28                                                                                        Employee.pm
29       $self->{ firstName } = shift() if ( @_ );
30
31       return $self->{ firstName };             Creates a new data member
32   }                                            that stores the first name of
33                                                the employee or returns the
34   sub lastName                                 value to the user
35   {
                                                                  Stores or returns the value
36      my $self = shift();
                                                                  of lastName of the user
37
38       $self->{ lastName } = shift() if ( @_ );
39
40       return $self->{ lastName };
41   }
42
43   sub hireDay
44   {                                            Sets or prints the value of hireDay
45      my $self = shift();
46
47       if ( @_ ) {
48          $self->{ hireDay }->setDate( @_ );
49       }
50       else {
51          $self->{ hireDay }->print();
52       }
53   }
54
 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                        Outline
 2   # Fig. 14.7: Hourly.pm
 3   # Implementation of class Hourly.
 4
                                                                                      Hourly.pm
 5   package Hourly;
 6
 7   use   strict;
 8   use   warnings;
 9   use   Employee;
                                                  @ISA is used to implement
10   our   @ISA = ( "Employee" );
11
                                                  class Employee
12   sub new
13   {
14      my $object = shift();
                                                               The new constructor
15      my $class = ref( $object ) || $object;                 creates an hourly object
16
17         my $self = $class->SUPER::new();
                                                            The SUPER keyword is used to
18         $self->{ rate } = undef;
                                                            call the new method of
19
20         bless( $self, $class );
                                                            Employee, the class we are
21         return $self;
                                                            inheriting from
22   }
23




 2001 Prentice Hall, Inc. All rights reserved.
24 sub rate                                                                           Outline
25 {
26      my $self = shift();                                                   Hourly.pm
27
                                                  Sets the rate to which the hourly
28      $self->{ rate } = shift() if ( @_ );
                                                  employee makes per hour
29
30      return $self->{ rate };
31 }
32




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                Outline
 2   # fig. 14.8: fig14_08.pl
 3   # Using classes Hourly and Employee
 4                                                                         fig14_08.pl
 5   use   strict;
 6   use   warnings;               The program uses both
 7   use   Employee;               Employee and Hourly
 8   use   Hourly;
 9
10   my $worker = new Hmployee;
11
12   $worker->firstName( "Jason" );
13   $worker->lastName( "Black" );
14   $worker->hireDay( 8, 5, 1995 );                     Sets the values of firstName,
15   print( $worker->firstName(), " ",                   lastName and hireDay
16          $worker->lastName(), " was hired on " );
17   $worker->hireDay();
18   print( ".\n\n" );             Prints out the data just
19                                  entered by getting them from
20   my $hour = new Hourly;         the object’s data members
21
22 $hour->firstName( "John" );
23 $hour->lastName( "White" );
                                                Sets the values of firstName,
24 $hour->hireDay( 11, 30, 1999 );
                                                lastName, hireDay and rate
25 $hour->rate( 9.50 );
26 print( $hour->firstName(), " ", $hour->lastName(),
27           " was hired on " );
28 $hour->hireDay();
29 print( ".\n" );
30 printf( "He makes \$%.2f per hour.\n", $hour->rate() );
 2001 Prentice Hall, Inc. All rights reserved.
Jason Black was hired on 8/5/1995.                       Outline
John White was hired on 11/30/1999.
He makes $9.50 per hour.                          fig14_08.pl
                                                  Program Output




 2001 Prentice Hall, Inc. All rights reserved.
                                  14.5 Overriding Methods

      • Method overriding
              – Redefine an inherited method in a derived class
              – Uses that class over the base class
              – Derived class methods take precedence over base class
                methods




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                           Outline
 2   # Fig. 14.9: Employee2.pm
 3   # Implementation of class Employee2.
 4                                                                                 Employee2.pm
 5   package Employee2;
 6
 7   use strict;
 8   use warnings;
 9   use Date;
10
11   sub new
                                                  The new constructor creates a new
12   {                                    object       of the right type.
13      my $object = shift();
14      my $class = ref( $object ) || $object;
15
16      my $self = { firstName => shift(),                     Each attribute is initialized
17                   lastName => shift(), };                   when the object is created
18
19      my $hireDay = new Date;                            In this employee class the hireDay
20
                                                           is actually a Date object
21      if ( $_[ 0 ] ) {
22         my ( $month, $day, $year ) = split( /\//, $_[ 0 ] );
23         $hireDay->day( $day );
24         $hireDay->month( $month );
25         $hireDay->year( $year );
26      }
27
28      $self->{ hireDay } = $hireDay;
29
30      bless( $self, $class );
 2001 Prentice Hall, Inc. All rights reserved.
31       return $self;                                                                        Outline
32   }
33
34   sub firstName                                                                      Employee2.pm
35   {                                            Get or sets the value of firstName
36      my $self = shift();
37
38       $self->{ firstName } = shift() if ( @_ );
39
40       return $self->{ firstName };
41   }
42
43   sub lastName
44   {
45      my $self = shift();
                                                      Get or sets the value of lastName
46
47       $self->{ lastName } = shift() if ( @_ );
48
49       return $self->{ lastName };
50   }
51
52   sub hireDay
53   {
54      my $self = shift();                          Get or sets the value of hireDay
55
56       if ( @_ ) {
57          $self->{ hireDay }->setDate( @_ );
58       }
59       else {
60          $self->{ hireDay }->print();
61       }
62   }
 2001 Prentice Hall, Inc. All rights reserved.
63                                                                                              Outline
64 sub write
65 {                                          Writes out all of the data about the user   Employee2.pm
66      my $self = shift();
67
68      print( "Hello, my name is ", $self->firstName, ".\n" );
69      print( "I was hired on " );
70      $self->hireDay();
71      print( ".\n" );
72 }
73




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl
 2   # Fig. 14.10: Hourly2.pm
                                                                             Outline
 3   # Implementation of class Hourly2.
 4                                                                     Hourly2.pm
 5   package Hourly2;
 6
 7   use   strict;
 8   use   warnings;
 9   use   Employee2;
                                 Inherits         Employee2
10   our   @ISA = ( "Employee2" );
11
12   sub new                              Uses the base class to get
13   {                                    the three data members
14      my $object = shift();
15      my $class = ref( $object ) || $object;
16
17         my $self = $class->SUPER::new( @_[ 0 .. 2 ]);
18         $self->{ rate } = $_[ 3 ];
19
20         bless( $self, $class );
21         return $self;
22   }
23
24   sub rate
25   {
26      my $self = shift();
27
28         $self->{ rate } = shift() if ( @_ );
29
30         return $self->{ rate };
31 }
 2001 Prentice Hall, Inc. All rights reserved.
32                                                                         Outline
33 sub write                      Base class is overridden
34 {
                                                                     Hourly2.pm
35      my $self = shift();
36      $self->SUPER::write();
37      printf( "I make \$%.2f per hour.\n", $self->rate );
38 }                         Calls the write method of the base
39                           class and then outputs the extra data




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl
 2   # Fig. 14.11: Boss.pm
                                                                                                Outline
 3   # Implementation of class Boss.
 4                                                                                        Boss.pm
 5   package Boss;
 6
 7   use   strict;
 8   use   warnings;
 9   use   Employee2;
                                                    Inherits Employee2
10   our   @ISA = ( "Employee2" );
11
12   sub new                              Uses the base class to get
13   {                                    the three data members
14      my $object = shift();
15      my $class = ref( $object ) || $object;
16
17         my $self    = $class->SUPER::new( @_[ 0 .. 2 ] );
18
19         $self->{ title } = $_[ 3 ];
20
21         bless( $self, $class );
22         return $self;
23   }
24                                                The new method, title, sets the rank
25   sub title
26   {
                                                  that the employee holds in the office
27      my $self = shift();
28
29         $self->{ title } = shift() if ( @_ );
30
31         return $self->{ title };
32   }
 2001 Prentice Hall, Inc. All rights reserved.
33
34 sub write                          The write method uses the Employee2           Outline
35 {                                  write method and also adds more to it
36      my $self = shift();                                                   Boss.pm
37
38      print( "My name is Mr. ", $self->lastName(), ".\n" );
39      print( "I am the boss and I am a ", $self->title(), ".\n" );
40 }
41




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                      Outline
2    # Fig. 14.12: fig14_12.pl
3    # Overriding base class methods.
                                                                                    fig14_12.pl
4
5    use strict;
6    use warnings;
7    use Employee2;
8    use Hourly2;                   Uses all three of the of the created classes.
9 use Boss;                         Employee2, Hourly2 and Boss
10
11 my $worker = new Employee2( "Jason", "Black", "8/5/1995" );
12
13 print( $worker->firstName(), " ",
14            $worker->lastName(), " was hired on " );
15 $worker->hireDay();
16 print( ".\n" );
                                           Creates a new Employee2 object
17 $worker->write();
                                           and specifies its data
18 print( "\n" );
19
20 my $hour = new Hourly2;
21
22 $hour->firstName( "John" );
                                                   Creates a new Hourly2 object
23 $hour->lastName( "White" );
24 $hour->hireDay( 11, 30, 1999 );
25 $hour->rate( 9.50 );
26 print( $hour->firstName(), " ",
27            $hour->lastName(), " was hired on " );

 2001 Prentice Hall, Inc. All rights reserved.
28 $hour->hireDay();                                                                     Outline
29 print( ".\n" );
30 printf( "This worker makes \$%.2f per hour.\n", $hour->rate()                   fig14_12.pl
);
31 $hour->write();
32 print( "\n" );
33
34 my $boss = new Boss;                           Creates a new Boss object, and
35
                                                  then sets and outputs its data
36 $boss->firstName( "George" );
37 $boss->lastName( "Red" );
38 $boss->hireDay( 5, 31, 1979 );
39 $boss->title( "manager" );
40 print( $boss->firstName(), " ",
41            $boss->lastName(), " is the boss.\n" );
42 print( "This worker was hired " );
43 $boss->hireDay();
44 print( " and their title is ", $boss->title(), ".\n" );
45 $boss->write();
46 print( "\n" );




 2001 Prentice Hall, Inc. All rights reserved.
Jason Black was hired on 8/5/1995.                                   Outline
Hello, my name is Jason.
I was hired on 8/5/1995.
                                                              fig14_12.pl
John White was hired on 11/30/1999.
This worker makes $9.50 per hour.                             Program Output
Hello, my name is John.
I was hired on 11/30/1999.
I make $9.50 per hour.

George Red is the boss.
This worker was hired 5/31/1979 and their title is manager.
My name is Mr. Red.
I am the boss and I am a manager.




 2001 Prentice Hall, Inc. All rights reserved.
          14.6 Other Class Relationships: Multiple
         Inheritance, Composition and Containment
      • Multiple inheritance
              – Adding more than one class to the @ISA array
                     • Depth first search
      • Composition
              – The “has a” relationship
              – One or more attributes that are of other classes
      • Containment
              – A class that can store objects of another class
              – Container classes




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                   Outline
 2   # Fig. 14.13: WorkGroup.pm
 3   # Implementation of class WorkGroup.
 4                                                                               WorkGroup.pm
 5   use   strict;
 6   use   warnings;                          Workgroup.pm inherits from
 7   use   Employee2;
 8   use   Hourly2;
                                              Employee2, Hourly2 and Boss
 9   use   Boss;
10
11   package WorkGroup;
12
13   sub new
14   {
15      my $object = shift();
16      my $class = ref( $object ) || $object;
17
18         my $group = [ @_ ];                    An anonymous array is
19                                                created to store employees
20         bless( $group, $class );
21         return $group;
22   }
23
24   sub add                                  The add method allow the user to
25   {                                        add a new employee to the list
26      my $object = shift();
27
28         foreach my $employee ( @_ ) {
29            push( @$object, $employee );
30         }
31   }
 2001 Prentice Hall, Inc. All rights reserved.
32                                                                                  Outline
33 sub listMembers
                                                  Lists all the members
34 {
                                                  that are contained within   WorkGroup.pm
35      my $object = shift();
                                                  the WorkGroup array
36
37      foreach my $employee ( @$object ) {
38           $employee->write();
39      }
40 }
41




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                          Outline
2    # Fig. 14.14: fig14_14.pl
3    # Demonstrating composition.
                                                                                        fig14_14.pl
4
5    use strict;
6    use warnings;
7    use Employee2;
8    use Hourly2;
9    use Boss;
                                                                  Creates a new Emplyee2 object
10 use WorkGroup;
11
12 my $worker = new Employee2( "Jason", "Black", "8/5/1995" );
13 my $hour = new Hourly2( "John", "White", "11/30/1999", 9.50 );
14
                                                                Creates a new Hourly2 object
15 my $group = new WorkGroup( $worker, $hour );
16                                                              Creates a new
17 my $boss = new Boss( "George", "Red",                        WorkGroup object
                                                     "5/31/1979", "manager" );
18                                                              and stores the two
19 $group->add( $boss );                                        new objects within it
20
21 $group->listMembers();
                                                            Creates a new boss abject
                               Lists everything in the arrayand adds to the array



 2001 Prentice Hall, Inc. All rights reserved.
Hello, my name is Jason.                                 Outline
I was hired on 8/5/1995.
Hello, my name is John.
I was hired on 11/30/1999.                        fig14_14.pl
I make $9.50 per hour.
My name is Mr. Red.                               Program Output
I am the boss and I am a manager.




 2001 Prentice Hall, Inc. All rights reserved.
                             14.7 Base Class UNIVERSAL

      • The UNIVERSAL class
              – Perl looks here after every other class
              – Want to add to all classes; add to UNIVERSAL class
              – The isa method
                     • Whether a class inherits from another class or not
              – The can method
                     • Whether a class has a particular implementation of a method




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                             Outline
2    # Fig. 14.15: fig14_15.pl
3    # Using the UNIVERSAL base class methods.
                                                                                           fig14_15.pl
4
5    use strict;
6    use warnings;
7    use Employee2;
8    use Hourly2;
9    use Boss;
10
11 my %people = ( employee => new Employee2,
12                        hourly        => new Hourly2,          Creates a hash with 3
13                        boss          => new Boss );           different objects in it
14
15 foreach my $key ( keys( %people ) ) {
16      my $object = $people{ $key };                     Loops for each key in the hash
                                                           Checks to see if each key in
17                                                         the hash is an Hourly2 if each key in the
                                                                       Checks to see
18      print( "$key is a employee2\n" )                               hash has the method rate
                                                           object
19           if $object->isa( 'Employee2' );
20      print( "$key is a hourly2\n" ) if $object->isa( 'Hourly2' );
21      print( "$key is a boss\n" ) if $object->isa( 'Boss' );
22      print( "$key can write\n" ) if $object->can( 'write' );
23      print( "$key can rate\n" ) if $object->can( 'rate' );
24      print( "$key can title\n" ) if $object->can( 'title' );
25      print( "\n" );
26 }

 2001 Prentice Hall, Inc. All rights reserved.
employee is a employee2                                  Outline
employee can write

boss   is a employee2                             fig14_15.pl
boss   is a boss
boss   can write                                  Program Output
boss   can title

hourly   is a employee2
hourly   is a hourly2
hourly   can write
hourly   can rate




 2001 Prentice Hall, Inc. All rights reserved.
               14.8 Encapsulation: Public vs. Private

      • Encapsulation
              – The hiding of data
              – Prevent a user from accessing certain parts of the program
                     • Helps to prevent updating errors
              – No private methods
                     • Trust programmer to use interface
                         – Do not use only if
                              » Accept the consequences
                              » Know what they are doing




 2001 Prentice Hall, Inc. All rights reserved.
                                       14.9 Closure Method

      • Closure
              – Can use deep binding and closure to “privatize” data
              – Variables in a closer are not available outside of the that
                closure
              – Must be called with the appropriate arguments
                     • One = key to be returned
                     • Two = key and new element for the key




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                              Outline
2    # Fig. 14.16: EmployeeClosure.pm
3    # Encapsulating data using closures.
                                                                                            EmployeeClosure.pm
4
5    package EmployeeClosure;
6
7    use strict;
8    use warnings;
9    use Date;
10
11 sub new
12 {                                                     Creates a reference to a closure
13      my $object = shift();
14      my $class = ref( $object ) || $object;
15
16      my $employee =          { firstName => shift(),
17                                 lastName => shift(), };
18
19      my $hireDay = new Date;
20
                                                  Will only pass the attributes
21      if ( $_[ 0 ] ) {
                                                  when sent the right arguments
22           my ( $month, $day, $year ) = split( /\//, $_[ 0 ] );
23           $hireDay->day( $day );
24           $hireDay->month( $month );
25           $hireDay->year( $year );
26      }
27
 2001 Prentice Hall, Inc. All rights reserved.
28       $employee->{ hireDay } = $hireDay;                                                  Outline
29
30       my $self = sub {
31                     my $field = shift();
                                                                                  EmployeeClosure.pm
32
33                            $employee->{ $field } = shift() if ( @_ );
34                            return $employee->{ $field };
35                       };
36
37       bless( $self, $class );                   The closure is blessed
38       return $self;                             to make an object
39   }
40
41   sub firstName
42   {
43      my $self = shift();                          Each get/set method calls the closure
44
                                                     by dereferencing the function
45       &{ $self }( "firstName", @_ );
46   }
47
48   sub lastName
49   {
50      my $self = shift();
51
52       &{ $self }( "lastName", @_ );
53   }
54


 2001 Prentice Hall, Inc. All rights reserved.
55 sub hireDay                                                                            Outline
56 {
57      my $self = shift();
                                                                                    EmployeeClosure.pm
58
59      my $date = &{ $self }( "hireDay" );
60
61      $date->setDate( @_ ) if ( @_ );
62
63      return $date;
64 }
65
66 sub write
67 {
68      my $self = shift();                       Displays the data of the object
69
70      print( "Hello, my name is ", $self->( 'firstName' ), ".\n"
);
71      print( "I was hired on " );
72
73      my $date = $self->( 'hireDay' );
74      $date->print();
75      print( ".\n" );
76 }
77
78 return 1;




 2001 Prentice Hall, Inc. All rights reserved.
 1    #!/usr/bin/perl                                                                           Outline
 2    # Fig. 14.17: fig14_17.pl
 3    # Using the EmployeeClosure class
 4
                                                                                         fig14_17.pl
 5    use strict;
 6    use warnings;
 7    use EmployeeClosure;
 8
                                                                                     Creates a new object
 9    my $first = new EmployeeClosure( "Jason", "Black", "8/5/1995" );
                                                                                     and sets its values
10    my $second = new EmployeeClosure;
11
12    $second->firstName( "John" );                             Sets the values of the
13    $second->lastName( "White" );                             EmployeeClosure object
14    $second->hireDay( 11, 30, 1999 );
15
16    $first->write();
17    $second->write();
                                                       Displays the data

 Hello, my name            is Jason.
 I was hired on            8/5/1995.                                                     Program Output
 Hello, my name            is John.
 I was hired on            11/30/1999.




      2001 Prentice Hall, Inc. All rights reserved.
                                   14.10 Implicit Functions

      • Explicit functions
              – Need to be called by the programmer
      • Implicit functions
              – Automatically called
              – Generally in all uppercase
                     • BEGIN
                     • END
                     • DESTROY
              – Most languages do not allow modification of them
              – Calling in a program is an error




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                 Outline
 2   # Fig. 14.18: Circular.pm
 3   # Using the DESTROY function to destroy objects.
 4                                                                             Circular.pm
 5   package Circular;
 6
 7   use strict;
 8   use warnings;
 9
10   sub new {
11      my $class = shift();
12
13       my $a;
14       my $b = \$a;
15
16       $a = \$b;
17
18       my $self = {};
19
20       $self->{ name } = shift();               Creates the new object
21       $self->{ Circle } = \$a;                 and returns it to the user
22
23       bless( $self, $class );
24       return $self;
25   }
26
27   sub sayHi {
28      my $self = shift();
29
30       print( "$self->{ name } says hi.\n" );
31   }
 2001 Prentice Hall, Inc. All rights reserved.
32                                                                               Outline
33 sub DESTROY {
                                              The DESTROY function;
                                                                           Circular.pm
34      my $self = shift();                   will execute automatically

35

36      print( "Destroying $self->{ name }.\n" );

37      ${ $self->{ Circle } } = undef;

38 }

39
40 return 1                               Displays the variable
                                          that went out of scope




 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                  Outline
 2   # Fig. 14.19: 19.pl
 3   # Demonstrating the DESTROY function.
 4                                                                            19.pl
 5   use warnings;
 6   use strict;
 7   use Circular;
 8
 9   my $a = new Circular( "Bob" );
10
11   {
12       print( "Entering First Scope.\n" );
13
14       my $b = new Circular( "Joe" );             Creates a new object
15
16       {
17           print( "Entering Second Scope.\n" );
18
19           my $c = new Circular( "Alice" );       Creates a new object
20           $c->sayHi();
21           print( "Exiting Second Scope.\n" );
22       }                                         When the Alice object’s scope
23                                                 ends the DESTROY function is
24       $b->sayHi();                              automatically called
25       print( "Exiting First Scope.\n" );
26   }                                            When the Joe object’s scope ends
27                                                the DESTROY function is again
28   $a->sayHi();                                 called automatically
29   print( "Exiting program.\n" );
 2001 Prentice Hall, Inc. All rights reserved.
Entering First Scope.                                     Outline
Entering Second Scope.
Alice says hi.
Exiting Second Scope.                             19.pl
Destroying Alice.
Joe says hi.                                      Program Output
Exiting First Scope.
Destroying Joe.
Bob says hi.
Exiting program.
Destroying Bob.




 2001 Prentice Hall, Inc. All rights reserved.
                                 14.11 AUTOLOAD Function

      • The AUTOLOAD function
              – Executes when a program cannot find a method in a class or
                any of its derived classes
              – The $AUTOLOAD variable receives the called name
              – Can also be used to prevent several set methods from doing
                the same thing with only different variables




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                         Outline
2    # Fig. 14.20: Date2.pm
3    # Implementation of autoloaded date2 class.
4                                                                                      Date2.pm
5    package Date2;
6    use strict;
7    use warnings;
8
9    my @months = (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
10
11   sub new
12   {
13      my $object = shift();
14      my $class = ref( $object ) || $object;
15
16       my $date = { year => 1000,
17                    month => 1,
18                    day => 1, };
19
20       bless( $date, $class );
21       return $date;
22   }                                            The AUTOLOAD function is called
23                                                whenever a call to a function is
24   sub AUTOLOAD                                 made that cannot be found
25   {
26      my $object = shift();
27      my $type = ref( $object ) ||                         Makes sure the method
28         die( "$object is not an object" );                was called on an object
29                                                            Store method
30     my $name = $Date2::AUTOLOAD;                           name into $name
 2001 Prentice Hall, Inc. All rights reserved.
31                                                                                    Outline
32       $name =~ s/.*://;
                                                  Eliminates the package name
33       exit() if ( $name eq 'DESTROY' );
34                                                                              Date2.pm
35       unless ( exists( $object->{ $name } ) ) {
36          die( "Cannot access '$name' field of class $type" );
37       }
38                            Makes sure the method
39       if ( @_ ) {          called was not DESTROY
40          return $object->{ $name } = shift();
41       }
42       else {
                                        Checks to see if a value was
43          return $object->{ $name };
                                        passed and if so, sets in the object
44       }
45   }
46
47   sub setDate
48   {
49      if ( @_ == 4 ) {
50         my $object = shift();
51
52           $object->year( $_[ 0 ] );
53           $object->month( $_[ 1 ] );
54           $object->day( $_[ 2 ] );
55       }
56       else {
57          print( "the .\n" );
58       }
59   }
60
 2001 Prentice Hall, Inc. All rights reserved.
61 sub print                                                                  Outline
62 {
                                                  Prints out the data
63      my $object = shift();
                                                                        Date2.pm
64      print( $object->month );
65      print( "/" );
66      print( $object->day );
67      print( "/" );
68      print( $object->year );
69 }
70




 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                Outline
2    # Fig. 14.21: fig14_21.pl
3    # Interface with autoloaded date2.pm.
                                                                             fig14_21.pl
4
5    use Date2;
6 use strict;
7    use warnings;
8
9    my $today = new Date2;
10
                                                  Sets and prints the date
11 $today->setDate( 2000, 7, 14 );
12 print $today->month(), "\n";
13 $today->print();


7                                                                            Program Output
7/14/2000




 2001 Prentice Hall, Inc. All rights reserved.
                                        14.12 Tied Variables

      • The STORE function
              – Called when setting the value of a scalar
              – By overriding it and using tie
                     • Can change a functionality of basic manipulations
                     • Can be used to hide the implementation of a class
      • The tie function
              – Two arguments
                     • First: the variable
                     • Second: the class to which it is being tied
      • The FETCH function
              – Gets the value of a tied variable


 2001 Prentice Hall, Inc. All rights reserved.
 1   #!/usr/bin/perl                                                                       Outline
 2   # Fig. 14.22: Queue.pm
 3   # Implementation of queue using a tied scalar.
 4                                                                                   Queue.pm
 5   package Queue;
 6   use strict;
 7   use warnings;
 8                                       Called when a tie function
 9   sub TIESCALAR                       receives a scalar as its first
10   {                                   argument
11      my ( $class ) = shift();
12      my @data = split( ' ', $_[ 0 ] );
13
14       bless( \@data, $class );
15       return \@data;
16   }
17
18   sub STORE         Takes the value and the             class
19   {                 and ties them together
20      my $obj = shift();
21      my $data = shift();
22                                                Assign values to the ties scalar
23       push( @$obj, $data );
24   }
25
26   sub FETCH                Used to retrieve the
27   {                        first value of the queue
28      my $obj = shift();
29      return shift( @$obj );
30   }
31
32   return 1;
     return 1;
 2001 Prentice Hall, Inc. All rights reserved.
1    #!/usr/bin/perl                                                                            Outline
2    # Fig. 14.23: fig14_23.pl
3    # Using a queue tied scalar.
                                                                                         fig14_23.pl
4
5    use Queue;
6    use strict;
7    use warnings;
8
9    my $line;
10
11 tie( $line, 'Queue', 'a b c d' );
12
13 print( "$line\n" );                      Prints each letter in the queue in
14 print( "$line\n" );                      the order they were inserted
15 $line = 'e';
16 $line = 'f';                                   Adds e and f to the end of the queue
17 print( "$line\n" );                            Continues to print the
18 print( "$line\n" );                            values in entered order
19 print( "$line\n" );


a                                                                                        Program Output
b
c
d
e




 2001 Prentice Hall, Inc. All rights reserved.

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:1
posted:2/10/2012
language:
pages:55