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

For one thing, yes, they do. References in Perl know what type of thing they reference to, and if that reference is blessed, they know what class they're blessed into. Furthermore, you don't have to do typecasting in Perl, nor does the compiler have to know what methods an object has at compile time. It is handled at runtime. Your 2nd snippet of code will work as is.

Update: since there seems to be some confusion about what I meant when I said "2nd snippet," this is the one I was talking about:

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);

That is, his post contains 3 snippets. The first stores the object in a package global, the 2nd stores the object in a lexical and passes it in, and the 3rd stores the object in a lexical but passes in a reference to it.


In reply to Re: Typecasting a scalar to a module by Mugatu
in thread 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.