Source

perl-begin / lib / tutorials / perl-for-newbies / lect3-all-in-one / objects / making / inheritance / Foo.pm

#
# Foo.pm
#
package Foo;

use strict;
use warnings;

sub new
{
    # Retrieve the package's string.
    # It is not necessarily Foo, because this constructor may be
    # called from a class that inherits Foo.
    my $class = shift;

    # $self is the the object. Let's initialize it to an empty hash
    # reference.
    my $self = {};
    
    # Associate $self with the class $class. This is probably the most
    # important step.
    bless $self, $class;

    # Now we can retrieve the other arguments passed to the 
    # constructor.
    
    my $name = shift || "Fooish";
    my $number = shift || 5;
    
    # Put these arguments inside class members
    $self->{'name'} = $name;
    $self->{'number'} = 5;

    # Return $self so the user can use it.
    return $self;
}

sub get_name
{
    # This step is necessary so it will be treated as a method
    my $self = shift;
    
    return $self->{'name'};
}

sub assign_name
{
    my $self = shift;

    # Notice that we can pass regular arguments from now on.
    my $new_name = shift || "Fooish";

    $self->{'name'} = $new_name;

    return 0;
}

1;
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.