Book Home Programming PerlSearch this book

31.9. use fields

In the Pet module:

package Pet;
use strict;
use fields qw(name weight _Pet_pid);
my $PID = 0;
sub new {
    my Pet $self = shift;
    unless (ref $self) {
        $self = fields::new($self);
        $self->{_Pet_pid} = "this is Pet's secret ID";
    }
    $self->{name} = "Hey, you!";
    $self->{weight} = 20;
    return $self;
}
1;
In a separate program, demopet:
use Pet;
my Pet $rock = new Pet;           # typed lexical

$rock->{name}     = "quartz";           
$rock->{weight}   = "2kg";
$rock->{_Pet_pid} = 1233;         # private attribute

$rock->{color}    = "blue";       # generates compile-time error
In the Dog module:
package Dog;
use strict;
use base 'Pet';                   # inherit fields and methods from Pet
use fields qw(name pedigree);     # override Pet name attribute,
                                  # add new pedigree attribute
use fields qw(wag _Dog_private);  # not shared with Pet
sub new {
    my $class = shift;
    my $self = fields::new($class);
    $self->SUPER::new();          # init base fields
    $self->{pedigree} = "none";   # init own fields
    return $self;
}
In a separate program, demodog:
use Dog;

my Dog $spot = new Dog;           # typed lexical

$spot->{name}     = "Theloneus";  # not inherited
$spot->{weight}   = "30lbs";      # inherited
$spot->{pedigree} = "mutt";       # not inherited

$spot->{color}    = "brown";      # generates compile-time error
$spot->{_Pet_pid} = 3324;         # generates compile-time error

The fields pragma provides a method of declaring class fields that can be type checked at compile time. This relies on a feature known as pseudohashes: if a typed lexical variable (my Pet $rock) is holding a reference (the Pet object) and is used to access a hash element ($rock->{name}), and if there exists a package with the same name as the declared type that has set up class fields using the fields pragma, then the operation is turned into an array access at compile time, provided the field specified is valid.

The related base pragma will combine fields from base classes and any fields declared using the fields pragma. This enables field inheritance to work properly.

Field names that start with an underscore character are made private to the class and are not visible to subclasses. Inherited fields can be overridden but will generate a warning if warnings are enabled.

The effect of all this is that you can have objects with named fields which are as compact as arrays and as fast to access. This only works as long as the objects are accessed through properly typed lexical variables, though. If the variables are not typed, access is only checked at run time, so your program runs slower because it has to do both a hash access and an array access. In addition to field declarations, the following functions are supported:

new

The fields::new function creates and blesses a pseudohash into the specified class (which may also be specified by passing an object of that class). The object is created with the fields declared earlier for that class using the fields pragma. This makes it possible to write a constructor like this:

package Critter::Sounds;
use fields qw(cat dog bird);

sub new {
    my Critter::Sounds $self = shift;
    $self = fields::new($self) unless ref $self;
    $self->{cat} = 'meow';                          # scalar element
    @$self{'dog','bird'} = ('bark','tweet');        # slice
    return $self;
}

phash

The fields::phash function creates and initializes a plain (unblessed) pseudohash. You should always use this function to create pseudohashes instead of creating them directly, in case we decide to change the implementation.

If the first argument to phash is a reference to an array, the pseudohash will be created with keys from that array. If a second argument is supplied, it must also be a reference to an array whose elements will be used as the values. If the second array contains less elements than the first, the trailing elements of the pseudohash will not be initialized. This makes it particularly useful for creating a pseudohash from subroutine arguments:

sub dogtag {
    my $tag = fields::phash([qw(name rank ser_num)], [@_]);
}
Alternatively, you can pass a list key/value pairs that will be used to construct the pseudohash:
my $tag = fields::phash(name => "Joe",
                        rank => "captain",
                        ser_num => 42);

my $pseudohash = fields::phash(%args);
For more on pseudohashes, see the section "Pseudohashes" in Chapter 8, "References".

The current implementation keeps the declared fields in the %FIELDS hash of the calling package, but this may change in future versions, so it's best to rely on this pragma's interface to manage your fields.



Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.