This is likely a sign of need for designing things in a more general way (subclass or something). However, sometimes there's already an established API to follow, and generalization is only available under the hood. In such cases I do like follows:

package Bark; use strict; use warnings; # more code here foreach (qw(cat dog)) { my $method_name = "function_$_"; # We're going to close over this variable # so it must be fresh in every loop iteration # don't use loop counter here my $impl = $_; # pre-caclucate more variables here if needed. # do whatever normal "sub $method {...}" would do # while we're still in strict mode my $code = sub { print $impl; }; # Finally, plant method - stricture is ONLY turned off # until end of scope i.e. for 1 line only no strict 'refs'; ## no critic # just in use "perlcritic" *$method_name = $code; }; 1;

This code can be tested (and actually was) with the following line:

perl -I. -MBark -we 'Bark->function_cat'

Note that I use $_ as loop variable because I have to reassign it anyway or ALL generated closures refer to the same var.

This sample is possibly in for further improvements but at least it allows to generalize code and have strictures on in the generated method/functions.


In reply to Re: Technique for building arguments from function name? by Dallaylaen
in thread Technique for building arguments from function name? by nysus

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.