in reply to Perl Object Initilization
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Perl Object Initilization
by tospo (Hermit) on Jun 10, 2011 at 10:02 UTC | |
by chromatic (Archbishop) on Jun 11, 2011 at 16:06 UTC | |
by tospo (Hermit) on Jun 14, 2011 at 12:22 UTC | |
by PyrexKidd (Monk) on Jun 11, 2011 at 23:32 UTC | |
|
Re^2: Perl Object Initilization
by 7stud (Deacon) on Jun 11, 2011 at 20:15 UTC |