DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Generic Object

04.08.2005
| 7131 views |
  • submit to reddit
        a generic object type thing for perl where you can use setanything and getanything to set and get properties via the AUTOLOAD method.
package thing;

use strict;

sub new {
	my %self;
	my ($class,@rest) = @_;
	unless ($#rest%2) { die "Odd parameter count\n"}
	for (my $k=0; $k<@rest; $k+=2) {
		my $wotsit = lc($rest[$k]);
		$wotsit =~ s/-//;
		$self{$wotsit} = $rest[$k+1];
		}
	bless \%self,$class;
}

sub AUTOLOAD {
        my ($where,$val) = @_;
        our $AUTOLOAD;
        $AUTOLOAD =~ s/.*://;
        my ($dirn,$what) = ($AUTOLOAD =~ /(...)(.*)/);
        if ($dirn eq "get") {
                return $$where{lc($what)};
        } elsif ($dirn eq "set") {
                $$where{lc($what)} = $val;
        }
        return 1;
}

1;


Here's a quick example of usage
use thing

$house = new thing("type","building","rooms",12,"foundations", "yes");

print $house -> gettype();
$house -> settype("tree");
print " " . $house -> gettype();