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

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.