Attribute-Handlers-Clean

 view release on metacpan or  search on metacpan

lib/Attribute/Handlers/Clean.pm  view on Meta::CPAN

=head2 Phase-specific attribute handlers

By default, attribute handlers are called at the end of the compilation
phase (in a C<CHECK> block). This seems to be optimal in most cases because
most things that can be defined are defined by that point but nothing has
been executed.

However, it is possible to set up attribute handlers that are called at
other points in the program's compilation or execution, by explicitly
stating the phase (or phases) in which you wish the attribute handler to
be called. For example:

    sub Early    :ATTR(SCALAR,BEGIN) {...}
    sub Normal   :ATTR(SCALAR,CHECK) {...}
    sub Late     :ATTR(SCALAR,INIT) {...}
    sub Final    :ATTR(SCALAR,END) {...}
    sub Bookends :ATTR(SCALAR,BEGIN,END) {...}

As the last example indicates, a handler may be set up to be (re)called in
two or more phases. The phase name is passed as the handler's final argument.

Note that attribute handlers that are scheduled for the C<BEGIN> phase
are handled as soon as the attribute is detected (i.e. before any
subsequently defined C<BEGIN> blocks are executed).


=head2 Attributes as C<tie> interfaces

Attributes make an excellent and intuitive interface through which to tie
variables. For example:

    use Attribute::Handlers::Clean;
    use Tie::Cycle;

    sub Cycle : ATTR(SCALAR) {
        my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
        $data = [ $data ] unless ref $data eq 'ARRAY';
        tie $$referent, 'Tie::Cycle', $data;
    }

    # and thereafter...

    package main;

    my $next : Cycle('A'..'Z');     # $next is now a tied variable

    while (<>) {
        print $next;
    }

Note that, because the C<Cycle> attribute receives its arguments in the
C<$data> variable, if the attribute is given a list of arguments, C<$data>
will consist of a single array reference; otherwise, it will consist of the
single argument directly. Since Tie::Cycle requires its cycling values to
be passed as an array reference, this means that we need to wrap
non-array-reference arguments in an array constructor:

    $data = [ $data ] unless ref $data eq 'ARRAY';

Typically, however, things are the other way around: the tieable class expects
its arguments as a flattened list, so the attribute looks like:

    sub Cycle : ATTR(SCALAR) {
        my ($package, $symbol, $referent, $attr, $data, $phase) = @_;
        my @data = ref $data eq 'ARRAY' ? @$data : $data;
        tie $$referent, 'Tie::Whatever', @data;
    }


This software pattern is so widely applicable that Attribute::Handlers::Clean
provides a way to automate it: specifying C<'autotie'> in the
C<use Attribute::Handlers::Clean> statement. So, the cycling example,
could also be written:

    use Attribute::Handlers::Clean autotie => { Cycle => 'Tie::Cycle' };

    # and thereafter...

    package main;

    my $next : Cycle(['A'..'Z']);     # $next is now a tied variable

    while (<>) {
        print $next;
    }

Note that we now have to pass the cycling values as an array reference,
since the C<autotie> mechanism passes C<tie> a list of arguments as a list
(as in the Tie::Whatever example), I<not> as an array reference (as in
the original Tie::Cycle example at the start of this section).

The argument after C<'autotie'> is a reference to a hash in which each key is
the name of an attribute to be created, and each value is the class to which
variables ascribed that attribute should be tied.

Note that there is no longer any need to import the Tie::Cycle module --
Attribute::Handlers::Clean takes care of that automagically. You can even pass
arguments to the module's C<import> subroutine, by appending them to the
class name. For example:

    use Attribute::Handlers::Clean autotie => { Dir => 'Tie::Dir qw(DIR_UNLINK)' };

If the attribute name is unqualified, the attribute is installed in the
current package. Otherwise it is installed in the qualifier's package:

    package Here;

    use Attribute::Handlers::Clean autotie => {
        Other::Good	=> Tie::SecureHash,	# tie attr installed in Other::
        Bad			=> Tie::Taxes,		# tie attr installed in Here:: and any subclass/caller of Here::
        Ugly		=> Software::Patent	# tie attr installed in Here:: and any subclass/caller of Here::
    };

Autoties are most commonly used in the module to which they actually tie, 
and need to export their attributes to any module that calls them. To
facilitate this, Attribute::Handlers::Clean recognizes a special "pseudo-class" --
C<__CALLER__>, which may be specified as the qualifier of an attribute:

    package Tie::Me::Kangaroo::Down::Sport;

    use Attribute::Handlers::Clean autotie => { '__CALLER__::Roo' => __PACKAGE__ };

lib/Attribute/Handlers/Clean.pm  view on Meta::CPAN

                              'CHECK',              # compiler phase
                            );

    MyClass::Omni:ATTR(HASH)( 'SomeOtherClass',     # class
                              'LEXICAL',            # no typeglob
                              \%hsh,                # referent
                              'Omni',               # attr name
                              'bus'                 # eval'd attr data
                              'CHECK',              # compiler phase
                            );


Installing handlers into UNIVERSAL, makes them... not the best idea. With L<Attribute::Handlers::Clean>, contrary to L<Attribute::Handlers>, you can simply:
For example:

    package Descriptions;
    use Attribute::Handlers::Clean;

    my %name;
    sub name { return $name{$_[2]}||*{$_[1]}{NAME} }

    sub Name :ATTR {
        $name{$_[2]} = $_[4];
    }

    sub Purpose :ATTR {
        print STDERR "Purpose of ", &name, " is $_[4]\n";
    }

    sub Unit :ATTR {
        print STDERR &name, " measured in $_[4]\n";
    }

Let's you write:

    package SomeClass;
    use Descriptions;

    my $capacity : Name(capacity)
                 : Purpose(to store max storage capacity for files)
                 : Unit(Gb);


    package Other;
    use SomeClass;
    
    sub foo : Purpose(to foo all data before barring it) { }

    # etc.

=head1 UTILITY FUNCTIONS

This module offers a single utility function, C<findsym()>.

=over 4

=item findsym

    my $symbol = Attribute::Handlers::Clean::findsym($package, $referent);

The function looks in the symbol table of C<$package> for the typeglob for
C<$referent>, which is a reference to a variable or subroutine (SCALAR, ARRAY,
HASH, or CODE). If it finds the typeglob, it returns it. Otherwise, it returns
undef. Note that C<findsym> memoizes the typeglobs it has previously
successfully found, so subsequent calls with the same arguments should be
much faster.

=back

=head1 DIAGNOSTICS

=over

=item C<Bad attribute type: ATTR(%s)>

An attribute handler was specified with an C<:ATTR(I<ref_type>)>, but the
type of referent it was defined to handle wasn't one of the five permitted:
C<SCALAR>, C<ARRAY>, C<HASH>, C<CODE>, or C<ANY>.

=item C<Attribute handler %s doesn't handle %s attributes>

A handler for attributes of the specified name I<was> defined, but not
for the specified type of declaration. Typically encountered when trying
to apply a C<VAR> attribute handler to a subroutine, or a C<SCALAR>
attribute handler to some other type of variable.

=item C<Declaration of %s attribute in package %s may clash with future reserved word>

A handler for an attributes with an all-lowercase name was declared. An
attribute with an all-lowercase name might have a meaning to Perl
itself some day, even though most don't yet. Use a mixed-case attribute
name, instead.

=item C<Can't have two ATTR specifiers on one subroutine>

You just can't, okay?
Instead, put all the specifications together with commas between them
in a single C<ATTR(I<specification>)>.

=item C<Can't autotie a %s>

You can only declare autoties for types C<"SCALAR">, C<"ARRAY">, and
C<"HASH">. They're the only things (apart from typeglobs -- which are
not declarable) that Perl can tie.

=item C<Internal error: %s symbol went missing>

Something is rotten in the state of the program. An attributed
subroutine ceased to exist between the point it was declared and the point
at which its attribute handler(s) would have been called.

=item C<Won't be able to apply END handler>

You have defined an END handler for an attribute that is being applied
to a lexical variable.  Since the variable may not be available during END
this won't happen.

=back

=head1 AUTHOR



( run in 1.658 second using v1.01-cache-2.11-cpan-5a3173703d6 )