Hello,
I have a feeling that this is easier than I am making it out to be, but I can't for the life of me figure out how to initialize values in an object.
Here's what works for me, but I would like to call an initialize subroutine.
#!/usr/bin/perl use strict; use warnings; package Obj; sub new { my $class = shift; my $self = { a => 20, }; bless $self, $class; return $self; } package main; my $obj = Obj->new; print $obj->{'a'};
What I would like to do is call an initialize sub, but all of the following attempts return an error:
Useless use of hash element in void context at obj.pl line 19.
I'm sure this is indicative of what I have done wrong, but I don't understand how this could be void context, since I'm assigning the values to the object...
#!/usr/bin/perl use strict; use warnings; package Obj; sub new { my $class = shift; my $self = {}; bless $self, $class; $self->initialize(); #$self->initialize($self, ); #initialize($self, ); #$self = initialize($self, ); #$self = $self->initialize($self); return $self; } sub initialize { my $self = shift; $self->{ 'a' => 10 }; } package main; my $obj = Obj->new; print $obj->{'a'};
ok, so apparently the following works, but what if I have multiple values? And what if I want to pass values to the initialize routine?
#!/usr/bin/perl use strict; use warnings; package Obj; sub new { my $class = shift; my $self = {}; bless $self, $class; $self->initialize(); return $self; } sub initialize { my $self = shift; $self->{ a } = 10; return $self; } package main; my $obj = Obj->new; print $obj->{'a'};
In reply to Perl Object Initilization by PyrexKidd
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |