Section 16.10. Coercions


16.10. Coercions

Specify coercions as :STRINGIFY, :NUMERIFY, and :BOOLIFY methods.

In addition to the :ATTR markers for attribute hashes, Class::Std also supplies markers for subroutines that implement conversions to numbers, strings, and booleans:

      sub count : NUMERIFY {    
# Call count( ) method whenever object used as number
my ($self, $ident) = @_; return scalar @{ $elements_of{$ident} }; } sub as_str : STRINGIFY {
# Call as_str( ) method whenever object used as string
my ($self, $ident) = @_; return sprintf '(%s)', join $COMMA, @{ $elements_of{$ident} }; } sub is_okay : BOOLIFY {
# Call is_okay( ) method whenever object used as boolean
my ($self) = @_; return !$self->Houston_We_Have_A_Problem( ); }

This provides a simpler, more convenient, and less repetitive interface than use overload:

      sub count {         my ($self) = @_;         return scalar @{ $elements_of{ident $self} };     }     sub as_str {         my ($self) = @_;         return sprintf '(%s)', join $COMMA, @{ $elements_of{ident $self} };     }     sub is_okay {         my ($self) = @_;         return !$self->Houston_We_Have_A_Problem( );     }     use overload (         q{0+}   => 'count',         q{""}   => 'as_str',         q{bool} => 'is_okay',         fallback => 1,     );



Perl Best Practices
Perl Best Practices
ISBN: 0596001738
EAN: 2147483647
Year: 2004
Pages: 350
Authors: Damian Conway

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net