#!/usr/bin/perl use strict; use warnings; package Thing; our $AUTOLOAD; #use vars '$AUTOLOAD'; sub new { my $class = shift; my $self = { @_ }; return bless $self, $class; } my %fields = ( color => 1, width => 1, height => 1, ); sub AUTOLOAD { my $self = shift; no strict 'refs'; my ($value) = @_; (my $key = $AUTOLOAD) =~ s/.*:://; # remove class name from key #print " AUTOLOAD: self='$self', autoload='$AUTOLOAD', value='$value', key='$key' \n"; return '' unless exists $fields{$key}; # Only do this for valid keys. # Create a subroutine so we won't need AUTOLOAD next time... *{$AUTOLOAD} = sub { $_[0]->{$key} = $_[1] if $_[1]; return $_[0]->{$key}}; # and do the right thing this time around. $self->{$key} = $value if $value; return $self->{$key} || ''; } package main; my $thing1 = new Thing( color => 'red' ); $thing1->height('6 feet'); #use Data::Dumper; #print Dumper($thing1); print " thing1 has color '" . $thing1->color() . "'\n"; print " and height '" . $thing1->height() . "'\n";