Old and Wise Monks,

I have come up with an interesting solution (I hope) to a tricky problem. I've almost got it but just need some advice.

I have a class, let's call it BigDB. I would like to dynamically generate object method names for a BigDB instance based upon some stuff read in from a file. Within the BigDB constructor, I say:

my $self = {}; # hash ref ... foreach my $method (@method_names_from_file) { $self->{$method} = makeCommandSub($stuff); }
And within makeCommandSub(), I am creating a code ref and returning it:
my $code = sub { my $self = shift; print "Dang, it worked.\n"; }; return $code;
So, I go ahead and create my new BigDB() object and everything seems to go fine. My debugger shows me that my new object $myDB now has CODE type fields:
$myDB <hash> ->{method1} <CODE> ->{method2} <CODE>
Alas, when I try to run these CODE blocks as I would a method, it doesn't work.
$myDB->method1();
yields...
Can't locate object method "method1" via package "BigDB" at line...
I have also tried &{$myDB->method1}. I AM able to run normal subroutines within the BigDB class.

So what's the proper way (if any) to execute these CODE refs in my object/hash ?

Much thanks

-zaven.pl


In reply to Dynamically Creating (and Calling) Object Methods by zaven

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.