Dear Monks,

I have some non-OO code that consists of data structure containing a rather large (60ish) number of code references, like so:
$CODEREFS{1}{1} = { property => 'value', ... cref => sub { ... } }; $CODEREFS{1}{2} = { property => 'value', ... cref => sub { ... } }; ...
At the time, this was created as a data structure because we needed a way to iterate through it and easily call a subset of the coderefs, and process the returned data.

Unfortunately, for various reasons this needs to be rewritten as an OO module, and those anonymous subs need access to the object data. I don't want to create 60+ subroutines named "sub mymodule_1_1", "sub mymodule_1_2" and so forth - and I'll still need to iterate through all of them somehow. I'm baffled by how to best achieve this- AUTOLOADER? Most of the subs are used in every invocation of the module.

Edit: I should've mentioned that not all the coderefs take the same number of arguments. I've done some testing and came up with this sort of solution, which keeps the anonymous subrefs:
package Blah; use strict; use warnings; require 5; use Carp; our %CODEREFS; $CODEREFS{1}{1} = { property => 'value', cref => sub { my $self = shift; } }; sub new { my $class = shift; my $self = { crefs => \%CODEREFS }; bless $self, $class; } sub access { my $self = shift; my ($a, $b) = (shift, shift); $self->{crefs}{$a}{$b}{cref}->($self, @_); } package main; use strict; my $blah = Blah->new(); $blah->access(1, 1);
Surely there must be a more elegant solution? Any help would be greatly appreciated,
-- telcontar

In reply to Refactoring a module with many anonymous subrefs as an OO module by telcontar

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.