Ah, HA! So I have to dereference $self to a hash then I can treat it as a hash. (DUH! right...)
I've always heard that it is bad practice to access an objects 'private' variables. I know this concept isn't enforced explicitly in Perl, but is there a good way to do this?
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; package Obj; sub new { my ($class, @args) = @_; my $self = {}; bless $self, $class; $self->init(@args); return $self; } sub init { my ($self, @args) = @_; %{$self} = ( a => 10, @args, ); return $self; } sub print_val_a { my $self = shift; # my $FHOUT = shift || "STDOUT"; # print $FHOUT $self->{'a'} . "\n"; print $self->{'a'} . "\n"; } package main; my $obj1 = Obj->new(); $obj1->print_val_a(); my $obj2 = Obj->new(a => 40); $obj2->print_val_a();
(Granted for some reason this: # my $FHOUT = shift || "STDOUT"; # print $FHOUT $self->{'a'} . "\n"; doesn't work as expected ...)
this works but then how do you control output direction? Is there a 'cleaner' way to do this?
and finally, how about destroying objects? according to perlobj, objects are destroyed automagically when they go out of scop, but what if I want to destroy them manually? as far as I can tell, calling a method DESTROY does not automatically destroy it... Is there even any reason to cleanup after your objects?
In reply to Re: Perl Object Initilization
by PyrexKidd
in thread Perl Object Initilization
by PyrexKidd
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |