BashingPerl BashingPerl - 1 year ago 102
Perl Question

Perl object inside the same module

The title is vague but I'll explain it.

I have a Perl script which uses a module named


I create an object inside the script

my $id = systemId->new({_dom => "dev"});

I am planning to instantiate an object similar to the one above but inside the

How do I do that?

I can't really search it on the net as I do not know what to search to begin with.

Answer Source

You can do it the same way you do it in a script. Similarly to how you can put the package and main:: in the same file, you can use the class in the package file once it is defined. See comments after code.

package Play;    
use warnings;
use strict;

sub new {
    my $class = shift;
    my $self = { _data => shift || 'default' }; 
    bless $self, $class;
    print "New object created.\n";
    return $self;

sub data {
    my $self = shift;
    if (@_) { $self->{_data} = shift }
    return $self->{_data};

print "Inside the package. Create object.\n";
my $obj = Play->new();
my $data = $obj->data();
print "data: $data\n";
print "\n";


The script

use warnings;
use strict;
use Play;

print "In main\n";
my $obj = Play->new(25);
print "data: " . $obj->data() . "\n";

Printout when running the script

Inside the package. Create object.
New object created.
data: default

In main
New object created.
data: 25

Once the bless call executed $self is an object of the class Play. From bless

bless REF
This function tells the thingy referenced by REF that it is now an object in the CLASSNAME package. If CLASSNAME is omitted, the current package is used. [...]

Since we are right in the package it can be used as an object and methods called on it. From perlobj

Once we've blessed the hash referred to by $self we can start calling methods on it.

This refers to working with $self hashref. Note that there are issues of initialization when it comes to creating an object and the question of what exactly is being done and how becomes important.

I can't help it but ask, what do you want to do with this?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download