Last active
August 29, 2015 14:04
-
-
Save Koitaro/873a4ee45c570c1ab8ee to your computer and use it in GitHub Desktop.
Slots - Perl module / Class builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Slots; | |
sub import { | |
shift; | |
my $pkg = caller; | |
my $index = -1; | |
eval join "\n", | |
"package $pkg;", | |
"\@${pkg}::ISA = 'Slots';", | |
map { $index++; "sub $_ { \$_[0][$index] }" } @_; | |
} | |
sub new { | |
my ($pkg, @arr) = @_; | |
bless \@arr, $pkg; | |
} | |
1; | |
__END__ | |
=pod | |
=head1 NAME | |
Slots | |
=head1 EXAMPLE | |
package Point; | |
use Slots qw(x y); | |
sub foo { ... } | |
package main; | |
my $obj = Point->new(3, 5); | |
print $obj->x, "\n"; | |
print $obj->y, "\n"; | |
=head1 AUTHOR | |
Yasusi Koibuti E<lt>yKoibuti@gmail.comE<gt> | |
=head1 COPYRIGHT | |
Copyright 2014 Yasusi Koibuti. | |
This program is free software; you can redistribute it | |
and/or modify it under the same terms as Perl itself. | |
=cut |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package SlotsLv; | |
sub import { | |
shift; | |
my $pkg = caller; | |
my $index = -1; | |
eval join "\n", | |
"package $pkg;", | |
"\@${pkg}::ISA = 'SlotsLv';", | |
map { $index++; "sub $_ : lvalue { \$_[0][$index] }" } @_; | |
} | |
sub new { | |
my ($pkg, @arr) = @_; | |
bless \@arr, $pkg; | |
} | |
1; | |
__END__ | |
=pod | |
=head1 NAME | |
SlotsLv | |
=head1 EXAMPLE | |
package Point; | |
use Slots qw(x y); | |
sub foo { ... } | |
package main; | |
my $obj = Point->new(3, 5); | |
print $obj->x, "\n"; | |
$obj->y = 10; | |
print $obj->y, "\n"; | |
=head1 AUTHOR | |
Yasusi Koibuti E<lt>yKoibuti@gmail.comE<gt> | |
=head1 COPYRIGHT | |
Copyright 2014 Yasusi Koibuti. | |
This program is free software; you can redistribute it | |
and/or modify it under the same terms as Perl itself. | |
=cut |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment