• Use a BEGIN block in the super class -- have AUTOLOAD create the functions right after the class is compiled.
  • Use a closure to generate your subs. Something like:
    sub gen_sub { my $self = shift; my $type = shift; my $sub_ref = sub { if (defined $self{$type}) { $value = $self{$type}; return $value; } else { return undef; } } *{"get_$type"} = $sub_ref; }
    [download]
    Actually, looking at it now, that would be good for an AUTOLOAD. Do something like:
    sub AUTOLOAD { no strict "refs"; my ($self, $value) = @_; # alias these to make it easier later if ($AUTOLOAD =~ /::get_(\w+)/) { *{$AUTOLOAD} = sub { return $_[0]->{$1} }; return $self->{$1}; } elsif ($AUTOLOAD =~ /::set_(\w+)/){ *{$AUTOLOAD} = sub { $_[0]->{$1} = $_[1] }; $self->[$1] = $value; return; } # handle other methods here or throw a warning }
    [download]
  • Tell people not to override AUTOLOAD without a good reason. If they have a good reason, figure out how to call your AUTOLOAD themselves. :)
  • Some other method... use $self->can($functionname) to see if an object has some method.
  • (good bits of code stolen from Object Oriented Perl, bad bits from me.)

    In reply to Other Options by chromatic
    in thread AUTOLOAD functions & inheritence by LunaticLeo

    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! —
    • How do I compose an effective node title?
    • How do I post a question effectively?
    • Markup in the Monastery
  • 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.