in reply to Typecasting a scalar to a module

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.

Replies are listed 'Best First'.
Re^2: Typecasting a scalar to a module
by Fletch (Bishop) on Mar 03, 2005 at 18:19 UTC

    Erm, no it won't work as is because he's passing a scalar reference to his object rather than the object ref itself.

    Update: Yup, confuzzlingness. I was reading "second snippet" as the second alternative, not the second code section as a whole.

      Huh? Where are the "scalar references" that are not "the object ref itself" in this code?

      my $local = a_module->new(); $local->do_init; func1($local); func2($local);

      Update: sorry for the confusion.

Re^2: Typecasting a scalar to a module
by thekestrel (Friar) on Mar 03, 2005 at 18:34 UTC
    Mugatu,
    I converted my script last night to the second method and it did actually complain about not knowing about the member functions (you'll have to excuse me if I'm mutilating the way you refer to each of these things), which prompted the question.
    After your comments I retried using the method I used in my second snippit as you suggested converted the entire program again and this time it worked. I'm not sure what I did wrong the first time, but it seems happy now and now I can initiate and manipulate multiple instances of everything. =)
    Thanks for clearing up how it all fit together.

    Regards Paul.