preface 
 
  Look_up Engine  
 
  email how to  
 
  counter  
 
  regex  
 
  search engine  
 
  home  
 
  ask us  
 

 

Perl scripting


Applications


OO Perl


Perl & Databases


Search a word:
   



© The scientific sentence. 2010

Perl Class, Object and methods
Making a class: Class, Object and methods

1. Declaring a class

To make a class named in Perl , just save a file with ".pm" extention, where we declare a package. Example:: #!C:/Perl/bin/perl.exe -w # declaring a package: #-------------------- package Books; # Construtor: #-------------- # The new function (subroutine) constructs an object: sub new { my $class = shift; my $self = { # Three attributes _discipline => shift, _field => shift, _pages => shift, }; bless $self, $class; return $self; } # bless() function returns a reference that becomes an object. # Define the two helper method Get and Set:

#1. Get (to get the value of a variable):

# 1.2. Books discipline sub get_discipline { my ( $self) = @_; return $self->{_discipline}; } # 1.1. Books field sub get_field { my ( $self) = @_; return $self->{_field}; } # 1.2. Books pages sub get_pages { my ( $self) = @_; return $self->{_pages}; }

#2.Set (to set a value of a variable):

#2.1. Books discipline: sub set_discipline { my ( $self, $discipline ) = @_; $self->{_discipline} = $discipline if defined($discipline); return $self->{_discipline}; } # 2.2. Books field: sub set_field { my ( $self, $field ) = @_; $self->{_field} = $field if defined($field ); return $self->{_field}; } # 2.3. Books pages: sub set_pages{ my ( $self, $pages) = @_; $self->{_pages} = $pages if defined($pages ); return $self->{_pages}; }

#3. Other methods:

# We can other methods, for example: sub _display { my ( $self) = @_; # Print all the values: print "This is a $self->{_discipline} Books. \n"; print "It is about $self->{_field}.\n"; print "It contains $self->{_pages} pages.\n"; } #_display(); 1; # The 1; here is important. It is set for confirmation.

#4. Other form for the constructor:

sub new { my $class = shift; my $self = { _discipline => shift, _field => shift, _pages => shift, }; # Printing the values : print "This is a $self->{_discipline} book. \n"; print "It is about $self->{_field}.\n"; print "It contains $self->{_pages} pages.\n"; bless $self, $class; return $self; # ... other functions ... } #We can also perm: print "$class"; $object = new Book( "Physics", "Mechanics", 980); (constructing an object)
  
Google
Web
ScientificSentence
 




chimie labs
|
scientific sentence
|
java
|
php
|
green cat
|
contact
|


© Scientificsentence 2007. All rights reserved.