Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

What you also can do is:

for my $prop (qw [field1 field2 field3]) { eval sprintf <<'END', ($prop) x 3; sub %s { my $self = shift; if (@_) {$self->{%s} = shift}; return $self->{%s}; } } END }

I used to generate accessors in this way, in part because I felt that glob manipulation was scary and turning off strictness, however temporarily, was fragile. Tom Christiansen eventually managed to convince me that the eval approach is bad - firstly it is wasteful of memory (and processor) because each method is recompiled afresh; secondly because it is deferred, and so a perl -c check won't show problems.

So these days I do it more like this:

for my $method (qw/ field1 field2 field3 /) { no strict 'refs'; *$method = sub { use strict 'refs'; my $self = shift; if (@_) {$self->{$method} = shift}; return $self->{$method}; }; }

Rather than creating 3 independent blocks of code, this creates 3 closures over the same block of code; in practice the resulting methods are otherwise identical. I also feel they are much easier to read this way, which is another aid for debugging and maintenance.

(I saw an alternative approach to the strictness here recently:

for my $method (qw/ ... /) { my $sub = sub { the code ... }; no strict 'refs'; *$method = $sub; }
.. which is probably better, but I haven't started using it yet.)

See Re: Things I Don't Use in Perl for some other things my autogenerated methods do.


In reply to Re^2: Self creating OO Module field accessors... by hv
in thread Self creating OO Module field accessors... by blue_cowdawg

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2022-05-28 19:43 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (101 votes). Check out past polls.