So I keep hearing (from various AI professors) how great lisp is. They're probably right. One of the big things is macros: how they allow you generate new code on the fly. While writing some nice, old-fashioned perl code, I noticed myself making a bunch of nearly-identical functions to set and retrieve values in my object, and thought "Wow! What we need here is macros!" So here's my take on it. My main question is whether there's a better way than using evals to do this; the second question is what's the better way in general to do this?

sub _setter_getter_maker { my $subname = shift; my $funcref; $funcref = eval<<"END"; sub { my(\$self, \$$subname) = \@_; \$self->{'$subname'} = \$$subname if defined \$$subname; return \$self->{'$subname'}; }; END return $funcref; }

The idea for use is basically thus:

my $pretend_object = {}; my $new_func = _setter_getter_maker($pretend_object, 'attrib'); #Now we can set a value for 'attrib' in this object $new_func->('value');

In reply to Pretending to be lisp: macros by anjiro

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.