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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.