Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

tomp http://www.sunnyblue.net/little/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

generic object

a generic object type thing for perl where you can use setanything and getanything to set and get properties via the AUTOLOAD method.
   1  
   2  package thing;
   3  
   4  use strict;
   5  
   6  sub new {
   7  	my %self;
   8  	my ($class,@rest) = @_;
   9  	unless ($#rest%2) { die "Odd parameter count\n"}
  10  	for (my $k=0; $k<@rest; $k+=2) {
  11  		my $wotsit = lc($rest[$k]);
  12  		$wotsit =~ s/-//;
  13  		$self{$wotsit} = $rest[$k+1];
  14  		}
  15  	bless \%self,$class;
  16  }
  17  
  18  sub AUTOLOAD {
  19          my ($where,$val) = @_;
  20          our $AUTOLOAD;
  21          $AUTOLOAD =~ s/.*://;
  22          my ($dirn,$what) = ($AUTOLOAD =~ /(...)(.*)/);
  23          if ($dirn eq "get") {
  24                  return $$where{lc($what)};
  25          } elsif ($dirn eq "set") {
  26                  $$where{lc($what)} = $val;
  27          }
  28          return 1;
  29  }
  30  
  31  1;
  32  


Here's a quick example of usage
   1  
   2  use thing
   3  
   4  $house = new thing("type","building","rooms",12,"foundations", "yes");
   5  
   6  print $house -> gettype();
   7  $house -> settype("tree");
   8  print " " . $house -> gettype();
   9  
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS