Skip to content

Instantly share code, notes, and snippets.

@Logioniz
Created April 13, 2015 09:10
Show Gist options
  • Save Logioniz/5dee58be16283332e2c6 to your computer and use it in GitHub Desktop.
Save Logioniz/5dee58be16283332e2c6 to your computer and use it in GitHub Desktop.
Example of AUTOLOAD
#!/usr/bin/perl
package A1;
use Data::Dumper;
our $AUTOLOAD;
sub new { my $class = shift; bless {@_}, ref $class || $class };
sub AUTOLOAD {
my $name = $AUTOLOAD;
return if $name =~ /^.*::[A-Z]+$/;
$name =~ s/^.*:://; # strip fully-qualified portion
warn 'Generate method';
my $sub = sub {
my $self = shift;
# Get
return $self->{$name} unless @_;
# Set
$self->{$name} = $_[0];
return $self;
};
no strict 'refs';
*{$AUTOLOAD} = $sub;
use strict 'refs';
goto &{$sub};
}
package main;
use Data::Dumper;
$\ = $/;
my $a1 = A1->new(www => 123456);
print $a1->www;
print $a1->www;
$a1->ttt(111);
print $a1->ttt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment