summaryrefslogtreecommitdiff
path: root/lib/fields.pm
blob: c2cf1d6a5df5c23a3bbf49a6b82021edc34c6adf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package fields;

=head1 NAME

fields - compile-time class fields

=head1 SYNOPSIS

    {
        package Foo;
        use fields qw(foo bar baz);
    }
    ...
    my Foo $var = new Foo;
    $var->{foo} = 42;

    # This will generate a compile-time error.
    $var->{zap} = 42;

=head1 DESCRIPTION

The C<fields> pragma enables compile-time verified class fields.

=cut

sub import {
    my $class = shift;
    my ($package) = caller;
    my $fields = \%{"$package\::FIELDS"};
    my $i = $fields->{__MAX__};
    foreach my $f (@_) {
	if (defined($fields->{$f})) {
	    require Carp;
	    Carp::croak("Field name $f already in use");
	}
	$fields->{$f} = ++$i;
    }
    $fields->{__MAX__} = $i;
}

1;