Hi Monks,

This might be a 101 question, but someone has to ask the silly ones. I have a scipt that operates on a global as such...


use a_module; my $global = a_module->new(); sub func1 { $global->do_something1(); } sub func2 { $global->do_something2(); } $global->do_init; func1(); func2();

The problem with this setup is that it is not re-entrant so if I wanted a $global and $global2 i'd have to duplicate everything which is just not on. So I think ok how about rewriting it as follows...

use a_module; sub func1 { my $var = $_[0]; $var->do_something1(); } sub func2 { my $var = $_[0]; $var->do_something2(); } my $local = a_module->new(); $local->do_init; func1($local); func2($local);

The problem with the above code is that the variables $var in both func1 and func2 don't know that they are supposed to be an instance of type a_module and hence don't have clue what the member functions do_something1 and do_something2 are.

This leads to the obvious question, how do i tell the scalars in the subroutines that they in fact a certain type? Is the only way to do it to pass a reference to the variable such that when you operate on it, it then knows about the member functions. Something like...

use a_module; sub func1 { my $var = $_[0]; $var->do_something1(); } sub func2 { my $var = $_[0]; $var->do_something2(); } my $local = a_module->new(); $local->do_init; func1(\$local); func2(\$local);

Thanks in advance for any thoughts =).
Regards Paul.


In reply to Typecasting a scalar to a module by thekestrel

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.