5 fields - compile-time class fields
11 use fields qw(foo bar _Foo_private);
15 $self = fields::new($self);
16 $self->{_Foo_private} = "this is Foo's secret";
24 my Foo $var = Foo::->new;
27 # this will generate a compile-time error
34 use fields qw(baz _Bar_private); # not shared with Foo
37 my $self = fields::new($class);
38 $self->SUPER::new(); # init base fields
39 $self->{baz} = 10; # init own fields
40 $self->{_Bar_private} = "this is Bar's secret";
47 The C<fields> pragma enables compile-time verified class fields.
49 NOTE: The current implementation keeps the declared fields in the %FIELDS
50 hash of the calling package, but this may change in future versions.
51 Do B<not> update the %FIELDS hash directly, because it must be created
52 at compile-time for it to be fully useful, as is done by this pragma.
54 If a typed lexical variable holding a reference is used to access a
55 hash element and a package with the same name as the type has declared
56 class fields using this pragma, then the operation is turned into an
57 array access at compile time.
59 The related C<base> pragma will combine fields from base classes and any
60 fields declared using the C<fields> pragma. This enables field
61 inheritance to work properly.
63 Field names that start with an underscore character are made private to
64 the class and are not visible to subclasses. Inherited fields can be
65 overridden but will generate a warning if used together with the C<-w>
68 The effect of all this is that you can have objects with named fields
69 which are as compact and as fast arrays to access. This only works
70 as long as the objects are accessed through properly typed variables.
71 If the objects are not typed, access is only checked at run time.
73 The following functions are supported:
79 fields::new() creates and blesses a pseudo-hash comprised of the fields
80 declared using the C<fields> pragma into the specified class.
81 This makes it possible to write a constructor like this:
83 package Critter::Sounds;
84 use fields qw(cat dog bird);
87 my Critter::Sounds $self = shift;
88 $self = fields::new($self) unless ref $self;
89 $self->{cat} = 'meow'; # scalar element
90 @$self{'dog','bird'} = ('bark','tweet'); # slice
96 fields::phash() can be used to create and initialize a plain (unblessed)
97 pseudo-hash. This function should always be used instead of creating
98 pseudo-hashes directly.
100 If the first argument is a reference to an array, the pseudo-hash will
101 be created with keys from that array. If a second argument is supplied,
102 it must also be a reference to an array whose elements will be used as
103 the values. If the second array contains less elements than the first,
104 the trailing elements of the pseudo-hash will not be initialized.
105 This makes it particularly useful for creating a pseudo-hash from
106 subroutine arguments:
109 my $tag = fields::phash([qw(name rank ser_num)], [@_]);
112 fields::phash() also accepts a list of key-value pairs that will
113 be used to construct the pseudo hash. Examples:
115 my $tag = fields::phash(name => "Joe",
119 my $pseudohash = fields::phash(%args);
126 L<perlref/Pseudo-hashes: Using an array as a hash>
133 use warnings::register;
134 our(%attr, $VERSION);
140 sub _PRIVATE () { 2 }
142 # The %attr hash holds the attributes of the currently assigned fields
143 # per class. The hash is indexed by class names and the hash value is
144 # an array reference. The first element in the array is the lowest field
145 # number not belonging to a base class. The remaining elements' indices
146 # are the field numbers. The values are integer bit masks, or undef
147 # in the case of base class private fields (which occupy a slot but are
148 # otherwise irrelevant to the class).
153 my $package = caller(0);
154 # avoid possible typo warnings
155 %{"$package\::FIELDS"} = () unless %{"$package\::FIELDS"};
156 my $fields = \%{"$package\::FIELDS"};
157 my $fattr = ($attr{$package} ||= [1]);
160 if ($next > $fattr->[0]
161 and ($fields->{$_[0]} || 0) >= $fattr->[0])
163 # There are already fields not belonging to base classes.
164 # Looks like a possible module reload...
168 my $fno = $fields->{$f};
170 # Allow the module to be reloaded so long as field positions
172 if ($fno and $fno != $next) {
174 if ($fno < $fattr->[0]) {
175 warnings::warnif("Hides field '$f' in base class") ;
177 Carp::croak("Field name '$f' already in use");
180 $fields->{$f} = $next;
181 $fattr->[$next] = ($f =~ /^_/) ? _PRIVATE : _PUBLIC;
184 if (@$fattr > $next) {
185 # Well, we gave them the benefit of the doubt by guessing the
186 # module was reloaded, but they appear to be declaring fields
187 # in more than one place. We can't be sure (without some extra
188 # bookkeeping) that the rest of the fields will be declared or
189 # have the same positions, so punt.
191 Carp::croak ("Reloaded module must declare all fields at once");
195 sub inherit { # called by base.pm when $base_fields is nonempty
196 my($derived, $base) = @_;
197 my $base_attr = $attr{$base};
198 my $derived_attr = $attr{$derived} ||= [];
199 # avoid possible typo warnings
200 %{"$base\::FIELDS"} = () unless %{"$base\::FIELDS"};
201 %{"$derived\::FIELDS"} = () unless %{"$derived\::FIELDS"};
202 my $base_fields = \%{"$base\::FIELDS"};
203 my $derived_fields = \%{"$derived\::FIELDS"};
205 $derived_attr->[0] = $base_attr ? scalar(@$base_attr) : 1;
206 while (my($k,$v) = each %$base_fields) {
208 if ($fno = $derived_fields->{$k} and $fno != $v) {
210 Carp::croak ("Inherited %FIELDS can't override existing %FIELDS");
212 if ($base_attr->[$v] & _PRIVATE) {
213 $derived_attr->[$v] = undef;
215 $derived_attr->[$v] = $base_attr->[$v];
216 $derived_fields->{$k} = $v;
221 sub _dump # sometimes useful for debugging
223 for my $pkg (sort keys %attr) {
225 if (@{"$pkg\::ISA"}) {
226 print " (", join(", ", @{"$pkg\::ISA"}), ")";
229 my $fields = \%{"$pkg\::FIELDS"};
230 for my $f (sort {$fields->{$a} <=> $fields->{$b}} keys %$fields) {
231 my $no = $fields->{$f};
233 my $fattr = $attr{$pkg}[$no];
234 if (defined $fattr) {
236 push(@a, "public") if $fattr & _PUBLIC;
237 push(@a, "private") if $fattr & _PRIVATE;
238 push(@a, "inherited") if $no < $attr{$pkg}[0];
239 print "\t(", join(", ", @a), ")";
248 $class = ref $class if ref $class;
249 return bless [\%{$class . "::FIELDS"}], $class;
256 if (ref $_[0] eq 'ARRAY') {
261 unless (! @_ and ref $v eq 'ARRAY') {
263 Carp::croak ("Expected at most two array refs\n");
270 Carp::croak ("Odd number of elements initializing pseudo-hash\n");
273 @$h{grep ++$i % 2, @_} = 1 .. @_ / 2;
275 $v = [grep $i++ % 2, @_];