Domanda

another question. I have this constructor:

sub constructor {
 my $class = shift;
 my $point = {
  year => 2013,
  month = 'june',
  @_,
 };

bless $point,$class;
}

So if I instantiate that:

my $object = Exercises -> constructor (year => 2012,day => 'Monday');

What's the use of that overriden values inside the constructor? Can anyone site a good example wherein the default values inside the constructor are used?

and how do i access the hash inside the constructor?

i tried something this:

print $object -> %$point;

which is wrong, but I did that code above because when i print $object only. It says Classname=HASH(0x152d998). So I assume it's a hash.

My understanding is that I cant use variables inside because they are lexical. Am I right?

È stato utile?

Soluzione

and how do i access the hash inside the constructor?

Your hashref inside the constructor ($point) is the object. When you bless a reference you make it into an object.

So you can now do this:

print $point->{year};  # from inside constructor
...
print $object->{year}; # after construction

But accessing the private parts of the object isn't safe. I would suggest that you create accessors for it rather than manipulating the hash directly. E.g.

sub year {
    my $self = shift; # this is now the object
    if (@_) {
        $self->{year} = $_[0];
    }
    return $self->{year};
}

...
print $object->year(1984);
print $object->year;

What's the use of that overriden values inside the constructor? Can anyone site a good example wherein the default values inside the constructor are used?

Since you have provided default values in the constructor, those will be used if you called the constructor without any arguments.

my $object = Exercises->new;

But since you add @_ to the hashref at the end, they will override the defaults if you supply arguments to the constructor (and the hash keys correspond to the defaults).

My understanding is that I cant use variables inside because they are lexical. Am I right?

I'm not sure that I really understand your question here. You can use variables anywhere you want. You can refer to them as long as they are in scope, or you can pass variables into the constructor or some other method if you need to.

The passed-in variables are in @_ in your subroutines. Normally they get assigned to something else for readability. E.g.

my $self = shift; # this shifts from @_ implicitly
my %args = @_; # for hash args
my ($year, $month, $day) = @_;

Some additional tips

You can see the entire data structure with this:

use Data::Dumper;
print Dumper $object;

You might not be aware that you can also use modules that can help you create classes more quickly. Check out these:

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top