[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] do... while? SPOILER



I was very happy to see the Class::Struct solution posted
earlier by Adam Rice (). I've never run across Class::Struct
before and I think it will make my life much easier!

In the meantime, I normally use AUTOLOAD (typed from memory,
there may be errors...):

=====
package My::Class;

use strict;
use vars qw(
 %ATTRIBS $AUTOLOAD
);

%ATTRIBS = ( fname, 1, lname, 1, username, 1 );
$AUTOLOAD = '';
...
sub AUTOLOAD {
 my $self = shift;
 my $value = shift;
 my $request = $AUTOLOAD;
 $request =~ s/^.*:://;
 if ( exists $ATTRIBS{ $request } ) {
    $self->{attribs}->{$request} = $value if ( $value );
    return $self->{attribs}->{$request};
 }
 ...do other stuff as neede with $request...
}
=====

Just lop off {attribs} if you want the attributes to be off
the root. To add new attributes to the class, all you need
to do is add new key/value pairs to %ATTRIBS. I think I
cribbed this entire thing from Tom Christiansen's perltoot
(perldoc perltoot), but it's been so long I can't be sure.

Chris

Tushar Samant wrote:
> 
> > Was it fun? (I have fun rewriting this sort of stuff...)
> 
> Here is a sample of something I want to rewrite (this is not the
> actual code, just the pattern):
> 
>   package Object1;
> 
>   sub new {
>     my $class = shift;
>     my($a1, $a2) = @_;
>     my %self = (
>       'a1', $a1,
>       'a2', $a2,
>     );
>     bless \%self, $class;
>     return \%self;
>   }
> 
>   sub geta1 {
>     return $_[0]->{a1};
>   }
> 
>   sub geta2 {
>     return $_[0]->{a2};
>   }
> 
> And on and on, world without end, over 20 packages with a hundred attributes.
> No aggregates, no inheritance--nothing, absolutely nothing except hashes and
> get functions. (And incomprehensible error reporting, direct prints to stdout,
> C<die>s, finicky bounds-checking of unfathomable intent... but I digress.)
> 
> OK, it's funny. The trouble is, these are the sorts of programs which are
> used to "prove" that Perl is unwieldy and hard to maintain... because e.g.
> adding one attribute to one class turns into "maintenance". And the most
> humorous thing of all is: what was all this farcical abstraction for? Yes,
> "to separate implementation from interface". Sure. Now imagine trying to
> change the implementation...
> 
> I say--not only will *programmers* of Perl quickly get the same effect as
> the 20 solemn "classes" above, but they will actually enjoy it. Question:
> how would you do it?
> 
> PS: As I said, I -want- to rewrite this. But be assured that there will
> be people who will call it a waste of time, or cryptic, or hackish, and
> say don't fix what ain't broken, and generally act like they are Fred
> Brooks himself...

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe