Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Although I don't like using it, defining an <code>AUTOLOAD</code> subroutine is a way to create arbitrary classes on the fly. It's been a while since I used it, but it should look something like this:</p> <pre><code>package Local::Foo; sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } sub AUTOLOAD { my $self = shift; my $value = shift; our $AUTOLOAD; (my $method = $AUTOLOAD) = s/.*:://; if ( defined $value ) { $self-&gt;{$method} = $value; } return $self-&gt;{$method}; } </code></pre> <p>This class <code>Local::Foo</code> has an infinite amount of methods. For example, if I said </p> <pre><code>$foo-&gt;bar("fubar"); </code></pre> <p>This would be the same as:</p> <pre><code>$foo-&gt;{bar} = "foobar"; </code></pre> <p>If i called <code>$foo-&gt;bar;</code>, it will return the value of <code>$foo-&gt;{bar};</code>.</p> <p>You probably want something to limit your method's style, and their values. For example, with this:</p> <pre><code>$foo-&gt;BAR; $foo-&gt;Bar; $foo-&gt;bar; </code></pre> <p>are all three valid and completely different methods. You probably want something to make sure your methods match a particular pattern (i.e., they're all lowercase, or the first letter is uppercase and the rest are lowercase. You probably want to make sure they start with a letter so, <code>$foo-&gt;23diba;</code> isn't a valid method.</p> <p>One little problem: Once you define an <code>AUTOLOAD</code> subroutine, you also define <code>DESTROY</code> subroutine too. Perl calls the <code>DESTROY</code> subroutine before an object is destroyed. You need to handle the issue if <code>$AUTOLOAD =~ /.*::DESTROY$/</code> too. You may need to add:</p> <pre><code>return if $AUTOLOAD =~ /.*::DESTROY$/; </code></pre> <p>somewhere in the <code>AUTOLOAD</code> subroutine, so you don't accidentally do something when <code>DESTROY</code> is called. Remember, it's automatically called whenever a class object falls out of scope if one exists, and with <code>AUTOLOAD</code>, you've defined one anyway.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload