Here's a slightly more complex version that creates actual methods on the fly so that you avoid the overhead of an AUTOLOAD method call on the second and successive calls.

It also uses magic GOTO, which is a cool hack in itself.

#!/usr/bin/perl -w
package myClass;
use strict;
use vars qw{$AUTOLOAD $Debug};

$Debug = 1;

sub new {
	return bless {
		thing	=> 1,
		thang	=> 2,
		thong	=> 3,
	}, shift;
}

sub AUTOLOAD {
	my $self = shift or return undef;

	# Get the called method name and trim off the fully-qualified part
	( my $method = $AUTOLOAD ) =~ s{.*::}{};

	# If the data member being accessed exists, build an accessor for it
	if ( exists $self->{$method} ) {

		### Create a closure that will become the new accessor method
		my $accessor = sub {
			my $closureSelf = shift;

			if ( @_ ) {
				return $closureSelf->{$method} = shift;
			}

			return $closureSelf->{$method};
		};

		# Assign the closure to the symbol table at the place where the real
		# method should be. We need to turn off strict refs, as we'll be mucking
	        # with the symbol table.
	  SYMBOL_TABLE_HACQUERY: {
			no strict qw{refs};
			*$AUTOLOAD = $accessor;
		}

		# Turn the call back into a method call by sticking the self-reference
		# back onto the arglist
		unshift @_, $self;

		# Jump to the newly-created method with magic goto
		goto &$AUTOLOAD;
	}

	### Handle other autoloaded methods or errors
}

DESTROY {}


### Test program
package main;

my $a = new myClass;

print $a->thing, $a->thang, $a->thong, "\n";

In reply to Re: How can I use AUTOLOAD to magically define get and set methods for my member data? by Perlmage
in thread How can I use AUTOLOAD to magically define get and set methods for my member data? by Anonymous Monk

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.