1package Class::Std;
2
3our $VERSION = '0.011';
4use strict;
5use warnings;
6use Carp;
7use Scalar::Util;
8
9use overload;
10
11BEGIN { *ID = \&Scalar::Util::refaddr; }
12
13my (%attribute, %cumulative, %anticumulative, %restricted, %private, %overload);
14
15my @exported_subs = qw(
16    new
17    DESTROY
18    AUTOLOAD
19    _DUMP
20);
21
22my @exported_extension_subs = qw(
23    MODIFY_HASH_ATTRIBUTES
24    MODIFY_CODE_ATTRIBUTES
25);
26
27sub import {
28    my $caller = caller;
29
30    no strict 'refs';
31    *{ $caller . '::ident'   } = \&Scalar::Util::refaddr;
32    for my $sub ( @exported_subs ) {
33        *{ $caller . '::' . $sub } = \&{$sub};
34    }
35    for my $sub ( @exported_extension_subs ) {
36        my $target = $caller . '::' . $sub;
37        my $real_sub = *{ $target }{CODE} || sub { return @_[2..$#_] };
38        no warnings 'redefine';
39        *{ $target } = sub {
40            my ($package, $referent, @unhandled) = @_;
41            for my $handler ($sub, $real_sub) {
42                next if !@unhandled;
43                @unhandled = $handler->($package, $referent, @unhandled);
44            }
45            return @unhandled;
46        };
47    }
48}
49
50sub _find_sub {
51    my ($package, $sub_ref) = @_;
52    no strict 'refs';
53    for my $name (keys %{$package.'::'}) {
54        my $candidate = *{$package.'::'.$name}{CODE};
55        return $name if $candidate && $candidate == $sub_ref;
56    }
57    croak q{Can't make anonymous subroutine cumulative};
58}
59
60sub _raw_str {
61    my ($pat) = @_;
62    return qr{ ('$pat') | ("$pat")
63             | qq? (?:
64                     /($pat)/ | \{($pat)\} | \(($pat)\) | \[($pat)\] | <($pat)>
65                   )
66             }xms;
67}
68
69sub _str {
70    my ($pat) = @_;
71    return qr{ '($pat)' | "($pat)"
72             | qq? (?:
73                     /($pat)/ | \{($pat)\} | \(($pat)\) | \[($pat)\] | <($pat)>
74                   )
75             }xms;
76}
77
78sub _extractor_for_pair_named {
79    my ($key, $raw) = @_;
80
81    $key = qr{\Q$key\E};
82    my $str_key = _str($key);
83
84    my $LDAB = "(?:\x{AB})";
85    my $RDAB = "(?:\x{BB})";
86
87    my $STR = $raw ? _raw_str( qr{.*?} ) : _str( qr{.*?} );
88    my $NUM = qr{ ( [-+]? (?:\d+\.?\d*|\.\d+) (?:[eE]\d+)? ) }xms;
89
90    my $matcher = qr{ :$key<  \s* ([^>]*) \s* >
91                    | :$key$LDAB  \s* ([^$RDAB]*) \s* $RDAB
92                    | :$key\( \s*  (?:$STR | $NUM )   \s* \)
93                    | (?: $key | $str_key ) \s* => \s* (?: $STR | $NUM )
94                    }xms;
95
96    return sub { return $_[0] =~ $matcher ? $+ : undef };
97}
98
99BEGIN {
100    *_extract_default  = _extractor_for_pair_named('default','raw');
101    *_extract_init_arg = _extractor_for_pair_named('init_arg');
102    *_extract_get      = _extractor_for_pair_named('get');
103    *_extract_set      = _extractor_for_pair_named('set');
104    *_extract_name     = _extractor_for_pair_named('name');
105}
106
107sub MODIFY_HASH_ATTRIBUTES {
108    my ($package, $referent, @attrs) = @_;
109    for my $attr (@attrs) {
110        next if $attr !~ m/\A ATTRS? \s* (?: \( (.*) \) )? \z/xms;
111        my ($default, $init_arg, $getter, $setter, $name);
112        if (my $config = $1) {
113            $default  = _extract_default($config);
114            $name     = _extract_name($config);
115            $init_arg = _extract_init_arg($config) || $name;
116
117            if ($getter = _extract_get($config) || $name) {
118                no strict 'refs';
119                *{$package.'::get_'.$getter} = sub {
120                    return $referent->{ID($_[0])};
121                }
122            }
123            if ($setter = _extract_set($config) || $name) {
124                no strict 'refs';
125                *{$package.'::set_'.$setter} = sub {
126                    croak "Missing new value in call to 'set_$setter' method"
127                        unless @_ == 2;
128                    my ($self, $new_val) = @_;
129                    my $old_val = $referent->{ID($self)};
130                    $referent->{ID($self)} = $new_val;
131                    return $old_val;
132                }
133            }
134        }
135        undef $attr;
136        push @{$attribute{$package}}, {
137            ref      => $referent,
138            default  => $default,
139            init_arg => $init_arg,
140            name     => $name || $init_arg || $getter || $setter || '????',
141        };
142    }
143    return grep {defined} @attrs;
144}
145
146sub _DUMP {
147    my ($self) = @_;
148    my $id = ID($self);
149
150    my %dump;
151    for my $package (keys %attribute) {
152        my $attr_list_ref = $attribute{$package};
153        for my $attr_ref ( @{$attr_list_ref} ) {
154            next if !exists $attr_ref->{ref}{$id};
155            $dump{$package}{$attr_ref->{name}} = $attr_ref->{ref}{$id};
156        }
157    }
158
159    require Data::Dumper;
160    my $dump = Data::Dumper::Dumper(\%dump);
161    $dump =~ s/^.{8}//gxms;
162    return $dump;
163}
164
165my $STD_OVERLOADER
166    = q{ package %%s;
167         use overload (
168            q{%s} => sub { $_[0]->%%s($_[0]->ident()) },
169            fallback => 1
170         );
171       };
172
173my %OVERLOADER_FOR = (
174    STRINGIFY => sprintf( $STD_OVERLOADER, q{""}   ),
175    NUMERIFY  => sprintf( $STD_OVERLOADER, q{0+}   ),
176    BOOLIFY   => sprintf( $STD_OVERLOADER, q{bool} ),
177    SCALARIFY => sprintf( $STD_OVERLOADER, q{${}}  ),
178    ARRAYIFY  => sprintf( $STD_OVERLOADER, q{@{}}  ),
179    HASHIFY   => sprintf( $STD_OVERLOADER, q{%%{}} ),  # %% to survive sprintf
180    GLOBIFY   => sprintf( $STD_OVERLOADER, q{*{}}  ),
181    CODIFY    => sprintf( $STD_OVERLOADER, q{&{}}  ),
182);
183
184sub MODIFY_CODE_ATTRIBUTES {
185    my ($package, $referent, @attrs) = @_;
186    for my $attr (@attrs) {
187        if ($attr eq 'CUMULATIVE') {
188            push @{$cumulative{$package}}, $referent;
189        }
190        elsif ($attr =~ m/\A CUMULATIVE \s* [(] \s* BASE \s* FIRST \s* [)] \z/xms) {
191            push @{$anticumulative{$package}}, $referent;
192        }
193        elsif ($attr =~ m/\A RESTRICTED \z/xms) {
194            push @{$restricted{$package}}, $referent;
195        }
196        elsif ($attr =~ m/\A PRIVATE \z/xms) {
197            push @{$private{$package}}, $referent;
198        }
199        elsif (exists $OVERLOADER_FOR{$attr}) {
200            push @{$overload{$package}}, [$referent, $attr];
201        }
202        undef $attr;
203    }
204    return grep {defined} @attrs;
205}
206
207my %_hierarchy_of;
208
209sub _hierarchy_of {
210    my ($class) = @_;
211
212    return @{$_hierarchy_of{$class}} if exists $_hierarchy_of{$class};
213
214    no strict 'refs';
215
216    my @hierarchy = $class;
217    my @parents   = @{$class.'::ISA'};
218
219    while (defined (my $parent = shift @parents)) {
220        push @hierarchy, $parent;
221        push @parents, @{$parent.'::ISA'};
222    }
223
224    my %seen;
225    return @{$_hierarchy_of{$class}}
226        = sort { $a->isa($b) ? -1
227               : $b->isa($a) ? +1
228               :                0
229               } grep !$seen{$_}++, @hierarchy;
230}
231
232my %_reverse_hierarchy_of;
233
234sub _reverse_hierarchy_of {
235    my ($class) = @_;
236
237    return @{$_reverse_hierarchy_of{$class}}
238        if exists $_reverse_hierarchy_of{$class};
239
240    no strict 'refs';
241
242    my @hierarchy = $class;
243    my @parents   = reverse @{$class.'::ISA'};
244
245    while (defined (my $parent = shift @parents)) {
246        push @hierarchy, $parent;
247        push @parents, reverse @{$parent.'::ISA'};
248    }
249
250    my %seen;
251    return @{$_reverse_hierarchy_of{$class}}
252        = reverse sort { $a->isa($b) ? -1
253                       : $b->isa($a) ? +1
254                       :                0
255                       } grep !$seen{$_}++, @hierarchy;
256}
257
258{
259    no warnings qw( void );
260    CHECK { initialize() }
261}
262
263sub initialize {
264    # Short-circuit if nothing to do...
265    return if keys(%restricted) + keys(%private)
266            + keys(%cumulative) + keys(%anticumulative)
267            + keys(%overload)
268                == 0;
269
270    my (%cumulative_named, %anticumulative_named);
271
272    # Implement restricted methods (only callable within hierarchy)...
273    for my $package (keys %restricted) {
274        for my $sub_ref (@{$restricted{$package}}) {
275            my $name = _find_sub($package, $sub_ref);
276            no warnings 'redefine';
277            no strict 'refs';
278            my $sub_name = $package.'::'.$name;
279            my $original = *{$sub_name}{CODE}
280                or croak "Restricted method ${package}::$name() declared ",
281                         'but not defined';
282            *{$sub_name} = sub {
283                my $caller;
284                my $level = 0;
285                while ($caller = caller($level++)) {
286                     last if $caller !~ /^(?: Class::Std | attributes )$/xms;
287                }
288                goto &{$original} if !$caller || $caller->isa($package)
289                                              || $package->isa($caller);
290                croak "Can't call restricted method $sub_name() from class $caller";
291            }
292        }
293    }
294
295    # Implement private methods (only callable from class itself)...
296    for my $package (keys %private) {
297        for my $sub_ref (@{$private{$package}}) {
298            my $name = _find_sub($package, $sub_ref);
299            no warnings 'redefine';
300            no strict 'refs';
301            my $sub_name = $package.'::'.$name;
302            my $original = *{$sub_name}{CODE}
303                or croak "Private method ${package}::$name() declared ",
304                         'but not defined';
305            *{$sub_name} = sub {
306                my $caller = caller;
307                goto &{$original} if $caller eq $package;
308                croak "Can't call private method $sub_name() from class $caller";
309            }
310        }
311    }
312
313    for my $package (keys %cumulative) {
314        for my $sub_ref (@{$cumulative{$package}}) {
315            my $name = _find_sub($package, $sub_ref);
316            $cumulative_named{$name}{$package} = $sub_ref;
317            no warnings 'redefine';
318            no strict 'refs';
319            *{$package.'::'.$name} = sub {
320                my @args = @_;
321                my $class = ref($_[0]) || $_[0];
322                my $list_context = wantarray;
323                my (@results, @classes);
324                for my $parent (_hierarchy_of($class)) {
325                    my $sub_ref = $cumulative_named{$name}{$parent} or next;
326                    ${$parent.'::AUTOLOAD'} = our $AUTOLOAD if $name eq 'AUTOLOAD';
327                    if (!defined $list_context) {
328                        $sub_ref->(@args);
329                        next;
330                    }
331                    push @classes, $parent;
332                    if ($list_context) {
333                        push @results, $sub_ref->(@args);
334                    }
335                    else {
336                        push @results, scalar $sub_ref->(@args);
337                    }
338                }
339                return if !defined $list_context;
340                return @results if $list_context;
341                return Class::Std::SCR->new({
342                    values  => \@results,
343                    classes => \@classes,
344                });
345            };
346        }
347    }
348
349    for my $package (keys %anticumulative) {
350        for my $sub_ref (@{$anticumulative{$package}}) {
351            my $name = _find_sub($package, $sub_ref);
352            if ($cumulative_named{$name}) {
353                for my $other_package (keys %{$cumulative_named{$name}}) {
354                    next unless $other_package->isa($package)
355                             || $package->isa($other_package);
356                    print STDERR
357                        "Conflicting definitions for cumulative method",
358                        " '$name'\n",
359                        "(specified as :CUMULATIVE in class '$other_package'\n",
360                        " but declared :CUMULATIVE(BASE FIRST) in class ",
361                        " '$package')\n";
362                    exit(1);
363                }
364            }
365            $anticumulative_named{$name}{$package} = $sub_ref;
366            no warnings 'redefine';
367            no strict 'refs';
368            *{$package.'::'.$name} = sub {
369                my $class = ref($_[0]) || $_[0];
370                my $list_context = wantarray;
371                my (@results, @classes);
372                for my $parent (_reverse_hierarchy_of($class)) {
373                    my $sub_ref = $anticumulative_named{$name}{$parent} or next;
374                    if (!defined $list_context) {
375                        &{$sub_ref};
376                        next;
377                    }
378                    push @classes, $parent;
379                    if ($list_context) {
380                        push @results, &{$sub_ref};
381                    }
382                    else {
383                        push @results, scalar &{$sub_ref};
384                    }
385                }
386                return if !defined $list_context;
387                return @results if $list_context;
388                return Class::Std::SCR->new({
389                    values  => \@results,
390                    classes => \@classes,
391                });
392            };
393        }
394    }
395
396    for my $package (keys %overload) {
397        foreach my $operation (@{ $overload{$package} }) {
398            my ($referent, $attr) = @$operation;
399            local $^W;
400            my $method = _find_sub($package, $referent);
401            eval sprintf $OVERLOADER_FOR{$attr}, $package, $method;
402            die "Internal error: $@" if $@;
403        }
404    }
405
406    # Remove initialization data to prevent re-initializations...
407    %restricted     = ();
408    %private        = ();
409    %cumulative     = ();
410    %anticumulative = ();
411    %overload       = ();
412}
413
414sub new {
415    my ($class, $arg_ref) = @_;
416
417    Class::Std::initialize();   # Ensure run-time (and mod_perl) setup is done
418
419    no strict 'refs';
420    croak "Can't find class $class" if ! keys %{$class.'::'};
421
422    croak "Argument to $class->new() must be hash reference"
423        if @_ > 1 && ref $arg_ref ne 'HASH';
424
425    my $new_obj = bless \my($anon_scalar), $class;
426    my $new_obj_id = ID($new_obj);
427    my (@missing_inits, @suss_keys);
428
429    $arg_ref ||= {};
430    my %arg_set;
431    BUILD: for my $base_class (_reverse_hierarchy_of($class)) {
432        my $arg_set = $arg_set{$base_class}
433            = { %{$arg_ref}, %{$arg_ref->{$base_class}||{}} };
434
435        # Apply BUILD() methods...
436        {
437            no warnings 'once';
438            if (my $build_ref = *{$base_class.'::BUILD'}{CODE}) {
439                $build_ref->($new_obj, $new_obj_id, $arg_set);
440            }
441        }
442
443        # Apply init_arg and default for attributes still undefined...
444        INITIALIZATION:
445        for my $attr_ref ( @{$attribute{$base_class}} ) {
446            next INITIALIZATION if defined $attr_ref->{ref}{$new_obj_id};
447
448            # Get arg from initializer list...
449            if (defined $attr_ref->{init_arg}
450                && exists $arg_set->{$attr_ref->{init_arg}}) {
451                $attr_ref->{ref}{$new_obj_id} = $arg_set->{$attr_ref->{init_arg}};
452
453                next INITIALIZATION;
454            }
455            elsif (defined $attr_ref->{default}) {
456                # Or use default value specified...
457                $attr_ref->{ref}{$new_obj_id} = eval $attr_ref->{default};
458
459                if ($@) {
460                    $attr_ref->{ref}{$new_obj_id} = $attr_ref->{default};
461                }
462
463                next INITIALIZATION;
464            }
465
466            if (defined $attr_ref->{init_arg}) {
467                # Record missing init_arg...
468                push @missing_inits,
469                     "Missing initializer label for $base_class: "
470                     . "'$attr_ref->{init_arg}'.\n";
471                push @suss_keys, keys %{$arg_set};
472            }
473        }
474    }
475
476    croak @missing_inits, _mislabelled(@suss_keys),
477          'Fatal error in constructor call'
478                if @missing_inits;
479
480    # START methods run after all BUILD methods complete...
481    for my $base_class (_reverse_hierarchy_of($class)) {
482        my $arg_set = $arg_set{$base_class};
483
484        # Apply START() methods...
485        {
486            no warnings 'once';
487            if (my $init_ref = *{$base_class.'::START'}{CODE}) {
488                $init_ref->($new_obj, $new_obj_id, $arg_set);
489            }
490        }
491    }
492
493    return $new_obj;
494}
495
496sub uniq (@) {
497    my %seen;
498    return grep { $seen{$_}++ } @_;
499}
500
501
502sub _mislabelled {
503    my (@names) = map { qq{'$_'} } uniq @_;
504
505    return q{} if @names == 0;
506
507    my $arglist
508        = @names == 1 ? $names[0]
509        : @names == 2 ? join q{ or }, @names
510        :               join(q{, }, @names[0..$#names-1]) . ", or $names[-1]"
511        ;
512    return "(Did you mislabel one of the args you passed: $arglist?)\n";
513}
514
515sub DESTROY {
516    my ($self) = @_;
517    my $id = ID($self);
518    push @_, $id;
519
520    for my $base_class (_hierarchy_of(ref $_[0])) {
521        no strict 'refs';
522        if (my $demolish_ref = *{$base_class.'::DEMOLISH'}{CODE}) {
523            &{$demolish_ref};
524        }
525
526        for my $attr_ref ( @{$attribute{$base_class}} ) {
527            delete $attr_ref->{ref}{$id};
528        }
529    }
530}
531
532sub AUTOLOAD {
533    my ($invocant) = @_;
534    my $invocant_class = ref $invocant || $invocant;
535    my ($package_name, $method_name) = our $AUTOLOAD =~ m/ (.*) :: (.*) /xms;
536
537    my $ident = ID($invocant);
538    if (!defined $ident) { $ident = $invocant }
539
540    for my $parent_class ( _hierarchy_of($invocant_class) ) {
541        no strict 'refs';
542        if (my $automethod_ref = *{$parent_class.'::AUTOMETHOD'}{CODE}) {
543            local $CALLER::_ = $_;
544            local $_ = $method_name;
545            if (my $method_impl
546                    = $automethod_ref->($invocant, $ident, @_[1..$#_])) {
547                goto &$method_impl;
548            }
549        }
550    }
551
552    my $type = ref $invocant ? 'object' : 'class';
553    croak qq{Can't locate $type method "$method_name" via package "$package_name"};
554}
555
556{
557    my $real_can = \&UNIVERSAL::can;
558    no warnings 'redefine', 'once';
559    *UNIVERSAL::can = sub {
560        my ($invocant, $method_name) = @_;
561
562        if ( defined $invocant ) {
563            if (my $sub_ref = $real_can->(@_)) {
564                return $sub_ref;
565            }
566
567            for my $parent_class ( _hierarchy_of(ref $invocant || $invocant) ) {
568                no strict 'refs';
569                if (my $automethod_ref = *{$parent_class.'::AUTOMETHOD'}{CODE}) {
570                    local $CALLER::_ = $_;
571                    local $_ = $method_name;
572                    if (my $method_impl = $automethod_ref->(@_)) {
573                        return sub { my $inv = shift; $inv->$method_name(@_) }
574                    }
575                }
576            }
577        }
578
579        return;
580    };
581}
582
583package Class::Std::SCR;
584use base qw( Class::Std );
585
586BEGIN { *ID = \&Scalar::Util::refaddr; }
587
588my %values_of  : ATTR( :init_arg<values> );
589my %classes_of : ATTR( :init_arg<classes> );
590
591sub new {
592    my ($class, $opt_ref) = @_;
593    my $new_obj = bless \do{my $scalar}, $class;
594    my $new_obj_id = ID($new_obj);
595    $values_of{$new_obj_id}  = $opt_ref->{values};
596    $classes_of{$new_obj_id} = $opt_ref->{classes};
597    return $new_obj;
598}
599
600use overload (
601    q{""}  => sub { return join q{}, grep { defined $_ } @{$values_of{ID($_[0])}}; },
602    q{0+}  => sub { return scalar @{$values_of{ID($_[0])}};    },
603    q{@{}} => sub { return $values_of{ID($_[0])};              },
604    q{%{}} => sub {
605        my ($self) = @_;
606        my %hash;
607        @hash{@{$classes_of{ID($self)}}} = @{$values_of{ID($self)}};
608        return \%hash;
609    },
610    fallback => 1,
611);
612
6131; # Magic true value required at end of module
614__END__
615
616=head1 NAME
617
618Class::Std - Support for creating standard "inside-out" classes
619
620
621=head1 VERSION
622
623This document describes Class::Std version 0.011
624
625
626=head1 SYNOPSIS
627
628    package MyClass;
629    use Class::Std;
630
631    # Create storage for object attributes...
632    my %name : ATTR;
633    my %rank : ATTR;
634    my %snum : ATTR;
635
636    my %public_data : ATTR;
637
638    # Handle initialization of objects of this class...
639    sub BUILD {
640        my ($self, $obj_ID, $arg_ref) = @_;
641
642        $name{$obj_ID} = check_name( $arg_ref->{name} );
643        $rank{$obj_ID} = check_rank( $arg_ref->{rank} );
644        $snum{$obj_ID} = _gen_uniq_serial_num();
645    }
646
647    # Handle cleanup of objects of this class...
648    sub DEMOLISH {
649        my ($self, $obj_ID) = @_;
650
651        _recycle_serial_num( $snum{$obj_ID} );
652    }
653
654    # Handle unknown method calls...
655    sub AUTOMETHOD {
656        my ($self, $obj_ID, @other_args) = @_;
657
658        # Return any public data...
659        if ( m/\A get_(.*)/ ) {  # Method name passed in $_
660            my $get_what = $1;
661            return sub {
662                return $public_data{$obj_ID}{$get_what};
663            }
664        }
665
666        warn "Can't call $method_name on ", ref $self, " object";
667
668        return;   # The call is declined by not returning a sub ref
669    }
670
671
672=head1 DESCRIPTION
673
674This module provides tools that help to implement the "inside out object"
675class structure in a convenient and standard way.
676
677I<Portions of the following code and documentation from "Perl Best Practices"
678copyright (c) 2005 by O'Reilly Media, Inc. and reprinted with permission.>
679
680=head2 Introduction
681
682Most programmers who use Perl's object-oriented features construct their
683objects by blessing a hash. But, in doing so, they undermine the
684robustness of the OO approach. Hash-based objects are unencapsulated:
685their entries are open for the world to access and modify.
686
687Objects without effective encapsulation are vulnerable. Instead of
688politely respecting their public interface, some clever client coder
689inevitably will realize that it's marginally faster to interact directly
690with the underlying implementation, pulling out attribute values
691directly from the hash of an object:
692
693    for my $file ( get_file_objs() ) {
694        print $file->{name}, "\n";
695    }
696
697instead of using the official interface:
698
699    for my $file ( get_file_objs() ) {
700        print $file->get_name(), "\n";
701    }
702
703From the moment someone does that, your class is no longer cleanly
704decoupled from the code that uses it. You can't be sure that any bugs in
705your class are actually caused by the internals of your class, and not
706the result of some kind of monkeying by the client code. And to make
707matters worse, now you can't ever change those internals without the
708risk of breaking some other part of the system.
709
710There is a simple, convenient, and utterly secure way to prevent client
711code from accessing the internals of the objects you provide. Happily,
712that approach also guards against misspelling attribute names (a common
713error in hash-based classes), as well as being just as fast as--and
714often more memory-efficient than--ordinary hash-based objects.
715
716That approach is referred to by various names--flyweight scalars,
717warehoused attributes, inverted indices--but most commonly it's known
718as: inside-out objects. Consider the following class definitions:
719
720    package File::Hierarchy;
721    {
722        # Objects of this class have the following attributes...
723        my %root_of;   # The root directory of the file hierarchy
724        my %files_of;  # Array storing object for each file in root directory
725
726        # Constructor takes path of file system root directory...
727        sub new {
728            my ($class, $root) = @_;
729
730            # Bless a scalar to instantiate the new object...
731            my $new_object = bless \do{my $anon_scalar}, $class;
732
733            # Initialize the object's "root" attribute...
734            $root_of{ident $new_object} = $root;
735
736            return $new_object;
737        }
738
739        # Retrieve files from root directory...
740        sub get_files {
741            my ($self) = @_;
742
743            # Load up the "files" attribute, if necessary...
744            if (!exists $files_of{ident $self}) {
745                $files_of{ident $self}
746                    = File::System->list_files($root_of{ident $self});
747            }
748
749            # Flatten the "files" attribute's array to produce a file list...
750            return @{ $files_of{ident $self} };
751        }
752    }
753
754    package File::Hierarchy::File;
755    {
756        # Objects of this class have the following attributes...
757        my %name_of;  # the name of the file
758
759        # Constructor takes name of file...
760        sub new {
761            my ($class, $filename) = @_;
762
763            # Bless a scalar to instantiate the new object...
764            my $new_object = bless \do{my $anon_scalar}, $class;
765
766            # Initialize the object's "name" attribute...
767            $name_of{ident $new_object} = $filename;
768
769            return $new_object;
770        }
771
772        # Retrieve name of file...
773        sub get_name {
774            my ($self) = @_;
775
776            return $name_of{ident $self};
777        }
778    }
779
780Unlike a hash-based class, each of these inside-out class is specified
781inside a surrounding code block:
782
783    package File::Hierarchy;
784    {
785        # [Class specification here]
786    }
787
788    package File::Hierarchy::File;
789    {
790        # [Class specification here]
791    }
792
793That block is vital, because it creates a limited scope, to which any
794lexical variables that are declared as part of the class will
795automatically be restricted.
796
797The next difference between the two versions of the classes is that each
798attribute of I<all> the objects in the class is now stored in a separate
799single hash:
800
801    # Objects of this class have the following attributes...
802
803    my %root_of;   # The root directory of the file hierarchy
804    my %files_of;  # Array storing object for each file in root directory
805
806This is 90 degrees to the usual hash-based approach. In hash-based
807classes, all the attributes of one object are stored in a single hash;
808in inside-out classes, one attribute from all objects is stored in a
809single hash. Diagrammatically:
810
811    Hash-based:
812                     Attribute 1      Attribute 2
813
814     Object A    { attr1 => $valA1,  attr2 => $val2 }
815
816     Object B    { attr1 => $valB1,  attr2 => $val2 }
817
818     Object C    { attr1 => $valB1,  attr2 => $val2 }
819
820
821
822    Inside-out:
823                      Object A           Object B          Object C
824
825    Attribute 1  { 19817 => $valA1,  172616 => $valB1,  67142 => $valC1 }
826
827    Attribute 2  { 19817 => $valA2,  172616 => $valB2,  67142 => $valC3 }
828
829    Attribute 3  { 19817 => $valA3,  172616 => $valB3,  67142 => $valC3 }
830
831So the attributes belonging to each object are distributed across a set of
832predeclared hashes, rather than being squashed together into one anonymous
833hash.
834
835This is a significant improvement. By telling Perl what attributes you
836expect to use, you enable the compiler to check--via use strict--that
837you do indeed use only those attributes.
838
839That's because of the third difference in the two approaches. Each
840attribute of a hash-based object is stored in an entry in the object's
841hash: C<< $self->{name} >>. In other words, the name of a hash-based attribute
842is symbolic: specified by the string value of a hash key. In contrast,
843each attribute of an inside-out object is stored in an entry of the
844attribute's hash: C<$name_of{ident $self}>. So the name of an inside-out
845attribute isn't symbolic; it's a hard-coded variable name.
846
847With hash-based objects, if an attribute name is accidentally misspelled
848in some method:
849
850    sub set_name {
851        my ($self, $new_name) = @_;
852
853        $self->{naem} = $new_name;             # Oops!
854
855        return;
856    }
857
858then the C<$self> hash will obligingly--and silently!--create a new entry
859in the hash, with the key C<'naem'>, then assign the new name to it. But
860since every other method in the class correctly refers to the attribute
861as C<$self->{name}>, assigning the new value to C<$self->{naem}> effectively
862makes that assigned value "vanish".
863
864With inside-out objects, however, an object's "name" attribute is stored
865as an entry in the class's lexical C<%name_of> hash. If the attribute name
866is misspelled then you're attempting to refer to an entirely different
867hash: C<%naem_of>. Like so:
868
869    sub set_name {
870        my ($self, $new_name) = @_;
871
872        $naem_of{ident $self} = $new_name;     # Kaboom!
873
874        return;
875    }
876
877But, since there's no such hash declared in the scope, use strict will
878complain (with extreme prejudice):
879
880    Global symbol "%naem_of" requires explicit package name at Hierarchy.pm line 86
881
882Not only is that consistency check now automatic, it's also performed at
883compile time.
884
885The next difference is even more important and beneficial. Instead of
886blessing an empty anonymous hash as the new object:
887
888    my $new_object = bless {}, $class;
889
890the inside-out constructor blesses an empty anonymous scalar:
891
892    my $new_object = bless \do{my $anon_scalar}, $class;
893
894That odd-looking C<\do{my $anon_scalar}> construct is needed because
895there's no built-in syntax in Perl for creating a reference to an
896anonymous scalar; you have to roll-your-own.
897
898The anonymous scalar is immediately passed to bless, which anoints it as
899an object of the appropriate class. The resulting object reference is
900then stored in C<$new_object>.
901
902Once the object exists, it's used to create a unique key
903(C<ident $new_object>) under which each attribute that belongs to the
904object will be stored (e.g. C<$root_of{ident $new_object}> or
905C<$name_of{ident $self}>). The C<ident()> utility that produces this unique
906key is provided by the Class::Std module and is identical in effect to
907the C<refaddr()> function in the standard Scalar::Util module.
908
909To recap: every inside-out object is a blessed scalar, and
910has--intrinsic to it--a unique identifying integer. That integer can be
911obtained from the object reference itself, and then used to access a
912unique entry for the object in each of the class's attribute hashes.
913
914This means that every inside-out object is nothing more than an
915unintialized scalar. When your constructor passes a new inside-out
916object back to the client code, all that comes back is an empty scalar,
917which makes it impossible for that client code to gain direct access to
918the object's internal state.
919
920Of the several popular methods of reliably enforcing encapsulation in
921Perl, inside-out objects are also by far the cheapest. The run-time
922performance of inside-out classes is effectively identical to that of
923regular hash-based classes. In particular, in both schemes, every
924attribute access requires only a single hash look-up. The only
925appreciable difference in speed occurs when an inside-out object is
926destroyed.
927
928Hash-based classes usually don't even have destructors. When the
929object's reference count decrements to zero, the hash is automatically
930reclaimed, and any data structures stored inside the hash are likewise
931cleaned up. This works so well that many OO Perl programmers find they
932never need to write a C<DESTROY()> method; Perl's built-in garbage
933collection handles everything just fine. In fact, the only time a
934destructor is needed is when objects have to manage resources outside
935that are not actually located inside the object, resources that need to
936be separately deallocated.
937
938But the whole point of an inside-out object is that its attributes are
939stored in allocated hashes that are not actually located inside the
940object. That's precisely how it achieves secure encapsulation: by not
941sending the attributes out into the client code.
942
943Unfortunately, that means when an inside-out object is eventually
944garbage collected, the only storage that is reclaimed is the single
945blessed scalar implementing the object. The object's attributes are
946entirely unaffected by the object's deallocation, because the attributes
947are not inside the object, nor are they referred to by it in any way.
948
949Instead, the attributes are referred to by the various attribute hashes
950in which they're stored. And since those hashes will continue to exist
951until the end of the program, the defunct object's orphaned attributes
952will likewise continue to exist, safely nestled inside their respective
953hashes, but now untended by any object. In other words, when an inside-
954out object dies, its associated attribute hashes leak memory.
955
956The solution is simple. Every inside-out class has to provide a
957destructor that "manually" cleans up the attributes of the object being
958destructed:
959
960    package File::Hierarchy;
961    {
962        # Objects of this class have the following attributes...
963        my %root_of;   # The root directory of the file hierarchy
964        my %files_of;  # Array storing object for each file in root directory
965
966        # Constructor takes path of file system root directory...
967        sub new {
968            # As before
969        }
970
971        # Retrieve files from root directory...
972        sub get_files {
973            # As before
974        }
975
976        # Clean up attributes when object is destroyed...
977        sub DESTROY {
978            my ($self) = @_;
979
980            delete $root_of{ident $self};
981            delete $files_of{ident $self};
982        }
983    }
984
985The obligation to provide a destructor like this in every inside-out
986class can be mildly irritating, but it is still a very small price to
987pay for the considerable benefits that the inside-out approach otherwise
988provides for free. And the irritation can easily be eliminated by using
989the appropriate class construction tools. See below.
990
991=head2 Automating Inside-Out Classes
992
993Perhaps the most annoying part about building classes in Perl (no matter how
994the objects are implemented) is that the basic structure of every class is
995more or less identical. For example, the implementation of the
996C<File::Hierarchy::File> class used in C<File::Hierarchy> looks like this:
997
998    package File::Hierarchy::File;
999    {
1000        # Objects of this class have the following attributes...
1001        my %name_of;  # the name of the file
1002
1003        # Constructor takes name of file...
1004        sub new {
1005            my ($class, $filename) = @_;
1006
1007            # Bless a scalar to instantiate the new object...
1008            my $new_object = bless \do{my $anon_scalar}, $class;
1009
1010            # Initialize the object's "name" attribute...
1011            $name_of{ident $new_object} = $filename;
1012
1013            return $new_object;
1014        }
1015
1016        # Retrieve name of file...
1017        sub get_name {
1018            my ($self) = @_;
1019
1020            return $name_of{ident $self};
1021        }
1022
1023        # Clean up attributes when object is destroyed...
1024        sub DESTROY {
1025            my ($self) = @_;
1026
1027            delete $name_of{ident $self};
1028        }
1029    }
1030
1031Apart from the actual names of the attributes, and their accessor methods,
1032that's exactly the same structure, and even the same code, as in the
1033C<File::Hierarchy> class.
1034
1035Indeed, the standard infrastructure of I<every> inside-out class looks
1036exactly the same. So it makes sense not to have to rewrite that standard
1037infrastructure code in every separate class.
1038
1039That's precisely what is module does: it implements the necessary
1040infrastructure for inside-out objects. See below.
1041
1042
1043=head1 INTERFACE
1044
1045=head2 Exported subroutines
1046
1047=over
1048
1049=item C<ident()>
1050
1051Class::Std always exports a subroutine called C<ident()>. This subroutine
1052returns a unique integer ID for any object passed to it.
1053
1054=back
1055
1056=head2 Non-exported subroutines
1057
1058=over
1059
1060=item C<Class::Std::initialize()>
1061
1062This subroutine sets up all the infrastructure to support your Class::Std-
1063based class. It is usually called automatically in a C<CHECK> block, or
1064(if the C<CHECK> block fails to run -- under C<mod_perl> or C<require
1065Class::Std> or C<eval "...">) during the first constructor call made to
1066a Class::Std-based object.
1067
1068In rare circumstances, you may need to call this subroutine directly yourself.
1069Specifically, if you set up cumulative, restricted, private, or automethodical
1070class methods (see below), and call any of them before you create any objects,
1071then you need to call C<Class::Std::initialize()> first.
1072
1073=back
1074
1075=head2 Methods created automatically
1076
1077The following subroutines are installed in any class that uses the
1078Class::Std module.
1079
1080=over
1081
1082=item C<new()>
1083
1084Every class that loads the Class::Std module automatically has a C<new()>
1085constructor, which returns an inside-out object (i.e. a blessed scalar).
1086
1087    $obj = MyClass->new();
1088
1089The constructor can be passed a single argument to initialize the
1090object. This argument must be a hash reference.
1091
1092    $obj = MyClass->new({ name=>'Foo', location=>'bar' });
1093
1094See the subsequent descriptions of the C<BUILD()> and C<START()> methods
1095and C<:ATTR()> trait, for an explanation of how the contents of this
1096optional hash can be used to initialize the object.
1097
1098It is almost always an error to implement your own C<new()> in any class
1099that uses Class::Std. You almost certainly want to write a C<BUILD()> or
1100C<START()> method instead. See below.
1101
1102
1103=item C<DESTROY()>
1104
1105Every class that loads the Class::Std module automatically has a C<DESTROY()>
1106destructor, which automatically cleans up any attributes declared with the
1107C<:ATTR()> trait (see below).
1108
1109It is almost always an error to write your own C<DESTROY()> in any class that
1110uses Class::Std. You almost certainly want to write your own C<DEMOLISH()>
1111instead. See below.
1112
1113
1114=item C<AUTOLOAD()>
1115
1116Every class that loads the Class::Std module automatically has an
1117C<AUTOLOAD()> method, which implements the C<AUTOMETHOD()> mechanism
1118described below.
1119
1120It is almost always an error to write your own C<AUTOLOAD()> in any class that
1121uses Class::Std. You almost certainly want to write your own C<AUTOMETHOD()>
1122instead.
1123
1124=item C<_DUMP()>
1125
1126This method returns a string that represents the internal state (i.e. the
1127attribute values) of the object on which it's called. Only those attributes
1128which are marked with an C<:ATTR> (see below) are reported. Attribute names
1129are reported only if they can be ascertained from an C<:init_arg>, C<:get>, or
1130C<:set> option within the C<:ATTR()>.
1131
1132Note that C<_DUMP()> is not designed to support full
1133serialization/deserialization of objects. See the separate
1134Class::Std::Storable module (on CPAN) for that.
1135
1136=back
1137
1138
1139=head2 Methods that can be supplied by the developer
1140
1141The following subroutines can be specified as standard methods of a
1142Class::Std class.
1143
1144=over
1145
1146=item C<BUILD()>
1147
1148When the C<new()> constructor of a Class::Std class is called, it
1149automatically calls every method named C<BUILD()> in I<all> the classes
1150in the new object's hierarchy. That is, when the constructor is called,
1151it walks the class's inheritance tree (from base classes downwards) and
1152calls every C<BUILD()> method it finds along the way.
1153
1154This means that, to initialize any class, you merely need to provide a
1155C<BUILD()> method for that class. You don't have to worry about ensuring
1156that any ancestral C<BUILD()> methods also get called; the constructor
1157will take care of that.
1158
1159Each C<BUILD()> method is called with three arguments: the invocant object,
1160the identifier number of that object, and a reference to (a customized version
1161of) the hash of arguments that was originally passed to the constructor:
1162
1163    sub BUILD {
1164        my ($self, $ident, $args_ref) = @_;
1165        ...
1166    }
1167
1168The argument hash is a "customized version" because the module
1169automatically does some fancy footwork to ensure that the arguments are
1170the ones appropriate to the class itself. That's because there's a
1171potential for collisions when Class::Std classes are used in a
1172hierarchy.
1173
1174One of the great advantages of using inside-out classes instead of hash-based
1175classes is that an inside-out base class and an inside-out derived
1176class can then each have an attribute of exactly the same name, which
1177are stored in separate lexical hashes in separate scopes. In a hash-based
1178object that's impossible, because the single hash can't have two
1179attributes with the same key.
1180
1181But that very advantage also presents something of a problem when
1182constructor arguments are themselves passed by hash. If two or more
1183classes in the name hierarchy do happen to have attributes of the same
1184name, the constructor will need two or more initializers with the name
1185key. Which a single hash can't provide.
1186
1187The solution is to allow initializer values to be partitioned into
1188distinct sets, each uniquely named, and which are then passed to the
1189appropriate base class. The easiest way to accomplish that is to pass
1190in a hash of hashes, where each top level key is the name of one of
1191the base classes, and the corresponding value is a hash of
1192initializers specifically for that base class.
1193
1194For example:
1195
1196    package Client;
1197    use Class::Std::Utils;
1198    {
1199        my %client_num_of :ATTR;  # Every client has a basic ID number
1200        my %name_of       :ATTR;
1201
1202        sub BUILD {
1203            my ($self, $ident, $arg_ref) = @_;
1204
1205            $client_num_of{$ident} = $arg_ref->{'Client'}{client_num};
1206            $name_of{$ident}       = $arg_ref->{'Client'}{client_name};
1207        }
1208    }
1209
1210    package Client::Corporate;
1211    use base qw( Client );
1212    use Class::Std::Utils;
1213    {
1214        my %client_num_of;     # Corporate clients have an additional ID number
1215        my %corporation_of;
1216        my %position_of;
1217
1218        sub BUILD {
1219            my ($self, $ident, $arg_ref) = @_;
1220
1221            $client_num_of{$ident}
1222                = $arg_ref->{'Client::Corporate'}{client_num};
1223            $corporation_of{$ident}
1224                = $arg_ref->{'Client::Corporate'}{corp_name};
1225            $position_of{$ident}
1226                = $arg_ref->{'Client::Corporate'}{position};
1227        }
1228    }
1229
1230    # and later...
1231
1232    my $new_client
1233        = Client::Corporate->new( {
1234            'Client' => {
1235                client_num  => '124C1',
1236                client_name => 'Humperdinck',
1237            },
1238            'Client::Corporate' => {
1239                client_num  => 'F_1692',
1240                corp_name   => 'Florin',
1241                position    => 'CEO',
1242            },
1243        });
1244
1245Now each class's C<BUILD()> method picks out only the initializer sub-hash
1246whose key is that class's own name. Since every class name is
1247different, the top-level keys of this multi-level initializer hash are
1248guaranteed to be unique. And since no single class can have two
1249identically named attributes, the keys of each second-level hash will be
1250unique as well. If two classes in the hierarchy both need an initializer
1251of the same name (e.g. 'client_num'), those two hash entries will now be
1252in separate sub-hashes, so they will never clash.
1253
1254Class::Std provides an even more sophisticated variation on this
1255functionality, which is generally much more convenient for the users of
1256classes. Classes that use Class::Std infrastructure allow both general
1257and class-specific initializers in the initialization hash. Clients only
1258need to specify classes for those initializers whose names actually are
1259ambiguous. Any other arguments can just be passed directly in the
1260top-level hash:
1261
1262    my $new_client
1263        = Client::Corporate->new( {
1264            client_name => 'Humperdinck',
1265            corp_name   => 'Florin',
1266            position    => 'CEO',
1267
1268            'Client'            => { client_num  => '124C1'  },
1269            'Client::Corporate' => { client_num  => 'F_1692' },
1270        });
1271
1272Class::Std also makes it easy for each class's C<BUILD()> to access
1273these class-specific initializer values. Before each C<BUILD()> is
1274invoked, the nested hash whose key is the same as the class name is
1275flattened back into the initializer hash itself. That is, C<Client::BUILD()>
1276is passed the hash:
1277
1278    {
1279        client_name => 'Humperdinck',
1280        corp_name   => 'Florin',
1281        position    => 'CEO',
1282        client_num  => '124C1',   # Flattened from 'Client' nested subhash
1283
1284        'Client'            => { client_num  => '124C1'  },
1285        'Client::Corporate' => { client_num  => 'F_1692' },
1286    }
1287
1288whereas C<Client::Corporate::BUILD()> is passed the hash:
1289
1290    {
1291        client_name => 'Humperdinck',
1292        corp_name   => 'Florin',
1293        position    => 'CEO',
1294        client_num  => 'F_1692',   # Flattened from 'Client::Corporate' subhash
1295
1296        'Client'            => { client_num  => '124C1'  },
1297        'Client::Corporate' => { client_num  => 'F_1692' },
1298    }
1299
1300This means that the C<BUILD()> method for each class can just assume that the
1301correct class-specific initializer values will available at the top level of
1302the hash. For example:
1303
1304        sub Client::BUILD {
1305            my ($self, $ident, $arg_ref) = @_;
1306
1307            $client_num_of{$ident} = $arg_ref->{client_num};    # '124C1'
1308            $name_of{$ident}       = $arg_ref->{client_name};
1309        }
1310
1311        sub Client::Corporate::BUILD {
1312            my ($self, $ident, $arg_ref) = @_;
1313
1314            $client_num_of{$ident}  = $arg_ref->{client_num};   # 'F_1692'
1315            $corporation_of{$ident} = $arg_ref->{corp_name};
1316            $position_of{$ident}    = $arg_ref->{position};
1317        }
1318
1319Both classes use the C<< $arg_ref->{client_num} >> initializer value, but
1320Class::Std automatically arranges for that value to be the right one for each
1321class.
1322
1323Also see the C<:ATTR()> marker (described below) for a simpler way of
1324initializing attributes.
1325
1326
1327=item C<START()>
1328
1329Once all the C<BUILD()> methods of a class have been called and any
1330initialization values or defaults have been subsequently applied to
1331uninitialized attributes, Class::Std arranges for any C<START()> methods
1332in the class's hierarchy to be called befre the constructor finishes.
1333That is, after the build and default initialization processes are
1334complete, the constructor walks down the class's inheritance tree a
1335second time and calls every C<START()> method it finds along the way.
1336
1337As with C<BUILD()>, each C<START()> method is called with three arguments:
1338the invocant object, the identifier number of that object, and a
1339reference to (a customized version of) the hash of arguments that was
1340originally passed to the constructor.
1341
1342The main difference between a C<BUILD()> method and a C<START()> method
1343is that a C<BUILD()> method runs before any attribute of the class is
1344auto-initialized or default-initialized, whereas a C<START()> method
1345runs after all the attributes of the class (including attributes in derived
1346classes) have been initialized in some way. So if you want to pre-empt
1347the initialization process, write a C<BUILD()>. But if you want to do
1348something with the newly created and fully initialized object, write a
1349C<START()> instead. Of course, any class can define I<both> a C<BUILD()>
1350and a C<START()> method, if that happens to be appropriate.
1351
1352
1353=item C<DEMOLISH()>
1354
1355The C<DESTROY()> method that is automatically provided by Class::Std ensures
1356that all the marked attributes (see the C<:ATTR()> marker below) of an object,
1357from all the classes in its inheritance hierarchy, are automatically cleaned
1358up.
1359
1360But, if a class requires other destructor behaviours (e.g. closing
1361filehandles, decrementing allocation counts, etc.) then you may need to
1362specify those explicitly.
1363
1364Whenever an object of a Class::Std class is destroyed, the C<DESTROY()>
1365method supplied by Class::Std automatically calls every method named
1366C<DEMOLISH()> in I<all> the classes in the new object's hierarchy. That
1367is, when the destructor is called, it walks the class's inheritance
1368tree (from derived classes upwards) and calls every C<DEMOLISH()> method it
1369finds along the way.
1370
1371This means that, to clean up any class, you merely need to provide a
1372C<DEMOLISH()> method for that class. You don't have to worry about ensuring
1373that any ancestral C<DEMOLISH()> methods also get called; the destructor
1374will take care of that.
1375
1376Each C<DEMOLISH()> method is called with two arguments: the invocant object,
1377and the identifier number of that object. For example:
1378
1379    sub DEMOLISH {
1380        my ($self, $ident) = @_;
1381
1382        $filehandle_of{$ident}->flush();
1383        $filehandle_of{$ident}->close();
1384    }
1385
1386Note that the attributes of the object are cleaned up I<after> the
1387C<DEMOLISH()> method is complete, so they may still be used within
1388that method.
1389
1390
1391=item C<AUTOMETHOD()>
1392
1393There is a significant problem with Perl's built-in C<AUTOLOAD> mechanism:
1394there's no way for a particular C<AUTOLOAD()> to say "no".
1395
1396If two or more classes in a class hierarchy have separate C<AUTOLOAD()>
1397methods, then the one belonging to the left-most-depth-first class in
1398the inheritance tree will always be invoked in preference to any others.
1399If it can't handle a particular call, the call will probably fail
1400catastrophically. This means that derived classes can't always be used
1401in place of base classes (a feature known as "Liskov substitutability")
1402because their inherited autoloading behaviour may be pre-empted by some
1403other unrelated base class on their left in the hierarchy.
1404
1405Class::Std provides a mechanism that solves this problem: the
1406C<AUTOMETHOD> method. An AUTOMETHOD() is expected to return either a
1407handler subroutine that implements the requested method functionality,
1408or else an C<undef> to indicate that it doesn't know how to handle the
1409request. Class::Std then coordinates every C<AUTOMETHOD()> in an object's
1410hierarchy, trying each one in turn until one of them produces a
1411suitable handler.
1412
1413The advantage of this approach is that the first C<AUTOMETHOD()> that's
1414invoked doesn't have to disenfranchise every other C<AUTOMETHOD()> in the
1415hierarchy. If the first one can't handle a particular method call, it
1416simply declines it and Class::Std tries the next candidate instead.
1417
1418Using C<AUTOMETHOD()> instead of C<AUTOLOAD()> makes a class
1419cleaner, more robust, and less disruptive in class hierarchies.
1420For example:
1421
1422    package Phonebook;
1423    use Class::Std;
1424    {
1425        my %entries_of : ATTR;
1426
1427        # Any method call is someone's name:
1428        # so store their phone number or get it...
1429        sub AUTOMETHOD {
1430            my ($self, $ident, $number) = @_;
1431
1432            my $subname = $_;   # Requested subroutine name is passed via $_
1433
1434            # Return failure if not a get_<name> or set_<name>
1435            # (Next AUTOMETHOD() in hierarchy will then be tried instead)...
1436            my ($mode, $name) = $subname =~ m/\A ([gs]et)_(.*) \z/xms
1437                or return;
1438
1439            # If get_<name>, return a handler that just returns the old number...
1440            return sub { return $entries_of{$ident}->{$name}; }
1441                if $mode eq 'get';
1442
1443            # Otherwise, set_<name>, so return a handler that
1444            # updates the entry and then returns the old number...
1445            return sub {
1446                $entries_of{$ident}->{$name} = $number;
1447                return;
1448            };
1449        }
1450    }
1451
1452    # and later...
1453
1454    my $lbb = Phonebook->new();
1455
1456    $lbb->set_Jenny(867_5309);
1457    $lbb->set_Glenn(736_5000);
1458
1459    print $lbb->get_Jenny(), "\n";
1460    print $lbb->get_Glenn(), "\n";
1461
1462Note that, unlike C<AUTOLOAD()>, an C<AUTOMETHOD()> is called with both the
1463invocant and the invocant's unique C<ident> number, followed by the actual
1464arguments that were passed to the method.
1465
1466Note too that the name of the method being called is passed as C<$_>
1467instead of C<$AUTOLOAD>, and does I<not> have the class name prepended
1468to it, so you don't have to strip that name off the front like almost
1469everyone almost always does in their C<AUTOLOAD()>. If your C<AUTOMETHOD()>
1470also needs to access the C<$_> from the caller's scope, that's still
1471available as C<$CALLER::_>.
1472
1473=back
1474
1475
1476=head2 Variable traits that can be ascribed
1477
1478The following markers can be added to the definition of any hash
1479used as an attribute storage within a Class::Std class
1480
1481=over
1482
1483=item C<:ATTR()>
1484
1485This marker can be used to indicate that a lexical hash is being used
1486to store one particular attribute of all the objects of the class. That is:
1487
1488    package File::Hierarchy;
1489    {
1490        my %root_of  :ATTR;
1491        my %files_of :ATTR;
1492
1493        # etc.
1494    }
1495
1496    package File::Hierarchy::File;
1497    {
1498        my %name_of;  :ATTR;
1499
1500        # etc.
1501    }
1502
1503Adding the C<:ATTR> marker to an attribute hash ensures that the corresponding
1504attribute belonging to each object of the class is automatically cleaned up
1505when the object is destroyed.
1506
1507The C<:ATTR> marker can also be given a number of options which automate
1508other attribute-related behaviours. Each of these options consists of a
1509key/value pair, which may be specified in either Perl 5 "fat comma" syntax
1510( C<< S<< key => 'value' >> >> ) or in one of the Perl 6 option syntaxes
1511( C<< S<< :key<value> >> >> or C<< S<< :key('value') >> >> or
1512C<< S<< :key�value� >> >>).
1513
1514Note that, due to a limitation in Perl itself, the complete C<:ATTR> marker,
1515including its options must appear on a single line.
1516interpolate variables into the option values
1517
1518=over
1519
1520=item C<< :ATTR( :init_arg<initializer_key> ) >>
1521
1522This option tells Class::Std which key in the constructor's initializer hash
1523holds the value with which the marked attribute should be initialized. That
1524is, instead of writing:
1525
1526    my %rank_of :ATTR;
1527
1528    sub BUILD {
1529        my ($self, $ident, $arg_ref) = @_;
1530
1531        $rank_of{$ident} = $arg_ref->{rank};
1532    }
1533
1534you can achieve the same initialization, by having Class::Std I<automatically>
1535pull that entry out of the hash and store it in the right attribute:
1536
1537    my %rank_of :ATTR( :init_arg<rank> );
1538
1539    # No BUILD() method required
1540
1541
1542=item C<< :ATTR( :default<compile_time_default_value> ) >>
1543
1544If a marked attribute is not initialized (either directly within a
1545C<BUILD()>, or automatically via an C<:init_arg> option), the constructor
1546supplied by Class::Std checks to see if a default value was specified
1547for that attribute. If so, that value is assigned to the attribute.
1548
1549So you could replace:
1550
1551    my %seen_of :ATTR;
1552
1553    sub BUILD {
1554        my ($self, $ident, $arg_ref) = @_;
1555
1556        $seen_of{$ident} = 0;  # Not seen yet
1557    }
1558
1559with:
1560
1561    my %seen_of :ATTR( :default(0) );
1562
1563    # No BUILD() required
1564
1565Note that only literal strings and numbers can be used as default values. A
1566common mistake is to write:
1567
1568    my %seen_of :ATTR( :default($some_variable) );
1569
1570But variables like this aren't interpolated into C<:ATTR> markers (this is a
1571limitation of Perl, not Class::Std).
1572
1573If your attribute needs something more complex, you will have to default
1574initialize it in a C<START()> method:
1575
1576    my %seen_of :ATTR;
1577
1578    sub START {
1579        my ($self, $id, $args_ref) = @_;
1580
1581        if (!defined $seen_of{$id}) {
1582            $seen_of{$id} = $some_variable;
1583        }
1584    }
1585
1586=item C<< :ATTR( :get<name> ) >>
1587
1588If the C<:get> option is specified, a read accessor is created for the
1589corresponding attribute. The name of the accessor is C<get_> followed by
1590whatever name is specified as the value of the C<:get> option. For example,
1591instead of:
1592
1593    my %current_count_of :ATTR;
1594
1595    sub get_count {
1596        my ($self) = @_;
1597
1598        return $current_count_of{ident($self)};
1599    }
1600
1601you can just write:
1602
1603    my %count_of :ATTR( :get<count> );
1604
1605Note that there is no way to prevent Class::Std adding the initial C<get_> to
1606each accessor name it creates. That's what "standard" means. See Chapter 15
1607of I<Perl Best Practices> (O'Reilly, 2005) for a full discussion on why
1608accessors should be named this way.
1609
1610=item C<< :ATTR( :set<name> ) >>
1611
1612If the C<:set> option is specified, a write accessor is created for the
1613corresponding attribute. The name of the accessor is C<set_> followed by
1614whatever name is specified as the value of the C<:set> option. For example,
1615instead of:
1616
1617    my %current_count_of :ATTR;
1618
1619    sub set_count {
1620        my ($self, $new_value) = @_;
1621
1622        croak "Missing new value in call to 'set_count' method"
1623            unless @_ == 2;
1624
1625        $current_count_of{ident($self)} = $new_value;
1626    }
1627
1628you can just write:
1629
1630    my %count_of :ATTR( :set<count> );
1631
1632Note that there is no way to prevent Class::Std adding the initial
1633C<set_> to each accessor name it creates. Nor is there any way to create
1634a combined "getter/setter" accessor. See Chapter 15 of I<Perl Best
1635Practices> (O'Reilly, 2005) for a full discussion on why accessors
1636should be named and implemented this way.
1637
1638=item C<< :ATTR( :name<name> ) >>
1639
1640Specifying the C<:name> option is merely a convenient
1641shorthand for specifying all three of C<:get>, C<:set>, and C<:init_arg>.
1642
1643=back
1644
1645You can, of course, specify two or more arguments in a single C<:ATTR()>
1646specification:
1647
1648    my %rank_of : ATTR( :init_arg<starting_rank>  :get<rank>  :set<rank> );
1649
1650
1651=item C<:ATTRS()>
1652
1653This is just another name for the C<:ATTR> marker (see above). The plural
1654form is convenient when you want to specify a series of attribute hashes in
1655the same statement:
1656
1657    my (
1658        %name_of,
1659        %rank_of,
1660        %snum_of,
1661        %age_of,
1662        %unit_of,
1663        %assignment_of,
1664        %medals_of,
1665    ) : ATTRS;
1666
1667=back
1668
1669=head2 Method traits that can be ascribed
1670
1671The following markers can be added to the definition of any subroutine
1672used as a method within a Class::Std class
1673
1674=over
1675
1676=item C<:RESTRICTED()>
1677
1678=item C<:PRIVATE()>
1679
1680Occasionally, it is useful to be able to create subroutines that can only be
1681accessed within a class's own hierarchy (that is, by derived classes). And
1682sometimes it's even more useful to be able to create methods that can only be
1683called within a class itself.
1684
1685Typically these types of methods are I<utility> methods: subroutines
1686that provide some internal service for a class, or a class hierarchy.
1687Class::Std supports the creation of these kinds of methods by providing two
1688special markers: C<:RESTRICTED()> and C<:PRIVATE()>.
1689
1690Methods marked C<:RESTRICTED()> are modified at the end of the
1691compilation phase so that they throw an exception when called from
1692outside a class's hierarchy. Methods marked C<:PRIVATE()> are modified
1693so that they throw an exception when called from outside the class in
1694which they're declared.
1695
1696For example:
1697
1698    package DogTag;
1699    use Class::Std;
1700    {
1701        my %ID_of   : ATTR;
1702        my %rank_of : ATTR;
1703
1704        my $ID_num = 0;
1705
1706        sub _allocate_next_ID : RESTRICTED {
1707            my ($self) = @_;
1708            $ID_of{ident $self} = $ID_num++;
1709            return;
1710        }
1711
1712        sub _check_rank : PRIVATE {
1713            my ($rank) = @_;
1714            return $rank if $VALID_RANK{$rank};
1715            croak "Unknown rank ($rank) specified";
1716        }
1717
1718        sub BUILD {
1719            my ($self, $ident, $arg_ref) = @_;
1720
1721            $self->_allocate_next_ID();
1722            $rank_of{$ident} = _check_rank($arg_ref->{rank});
1723        }
1724    }
1725
1726Of course, this code would run exactly the same without the C<:RESTRICTED()>
1727and C<:PRIVATE()> markers, but they ensure that any attempt to call the two
1728subroutines inappropriately:
1729
1730    package main;
1731
1732    my $dogtag = DogTag->new({ rank => 'PFC' });
1733
1734    $dogtag->_allocate_next_ID();
1735
1736is suitably punished:
1737
1738    Can't call restricted method DogTag::_allocate_next_ID() from class main
1739
1740
1741=item C<:CUMULATIVE()>
1742
1743One of the most important advantages of using the C<BUILD()> and C<DEMOLISH()>
1744mechanisms supplied by Class::Std is that those methods don't require
1745nested calls to their ancestral methods, via the C<SUPER> pseudo-class. The
1746constructor and destructor provided by Class::Std take care of the
1747necessary redispatching automatically. Each C<BUILD()> method can focus
1748solely on its own responsibilities; it doesn't have to also help
1749orchestrate the cumulative constructor effects across the class
1750hierarchy by remembering to call C<< $self->SUPER::BUILD() >>.
1751
1752Moreover, calls via C<SUPER> can only ever call the method of exactly one
1753ancestral class, which is not sufficient under multiple inheritance.
1754
1755Class::Std provides a different way of creating methods whose effects
1756accumulate through a class hierarchy, in the same way as those of
1757C<BUILD()> and C<DEMOLISH()> do. Specifically, the module allows you to define
1758your own "cumulative methods".
1759
1760An ordinary non-cumulative method hides any method of the same name
1761inherited from any base class, so when a non-cumulative method is
1762called, only the most-derived version of it is ever invoked. In
1763contrast, a cumulative method doesn't hide ancestral methods of the same
1764name; it assimilates them. When a cumulative method is called, the
1765most-derived version of it is invoked, then any parental versions, then any
1766grandparental versions, etc. etc, until every cumulative method of the
1767same name throughout the entire hierarchy has been called.
1768
1769For example, you could define a cumulative C<describe()> method to the various
1770classes in a simple class hierarchy like so:
1771
1772    package Wax::Floor;
1773    use Class::Std;
1774    {
1775        my %name_of    :ATTR( init_arg => 'name'   );
1776        my %patent_of  :ATTR( init_arg => 'patent' );
1777
1778        sub describe :CUMULATIVE {
1779            my ($self) = @_;
1780
1781            print "The floor wax $name_of{ident $self} ",
1782                  "(patent: $patent_of{ident $self})\n";
1783
1784            return;
1785        }
1786    }
1787
1788    package Topping::Dessert;
1789    use Class::Std;
1790    {
1791        my %name_of     :ATTR( init_arg => 'name'    );
1792        my %flavour_of  :ATTR( init_arg => 'flavour' );
1793
1794        sub describe :CUMULATIVE {
1795            my ($self) = @_;
1796
1797            print "The dessert topping $name_of{ident $self} ",
1798                  "with that great $flavour_of{ident $self} taste!\n";
1799
1800            return;
1801        }
1802    }
1803
1804    package Shimmer;
1805    use base qw( Wax::Floor  Topping::Dessert );
1806    use Class::Std;
1807    {
1808        my %name_of    :ATTR( init_arg => 'name'   );
1809        my %patent_of  :ATTR( init_arg => 'patent' );
1810
1811        sub describe :CUMULATIVE {
1812            my ($self) = @_;
1813
1814            print "New $name_of{ident $self} ",
1815                  "(patent: $patent_of{ident $self})\n",
1816                  "Combining...\n";
1817
1818            return;
1819        }
1820    }
1821
1822Because the various C<describe()> methods are marked as being cumulative, a
1823subsequent call to:
1824
1825    my $product
1826        = Shimmer->new({
1827              name    => 'Shimmer',
1828              patent  => 1562516251,
1829              flavour => 'Vanilla',
1830          });
1831
1832    $product->describe();
1833
1834will work its way up through the classes of Shimmer's inheritance tree
1835(in the same order as a destructor call would), calling each C<describe()>
1836method it finds along the way. So the single call to C<describe()> would
1837invoke the corresponding method in each class, producing:
1838
1839    New Shimmer (patent: 1562516251)
1840    Combining...
1841    The floor wax Shimmer (patent: 1562516251)
1842    The dessert topping Shimmer with that great Vanilla taste!
1843
1844Note that the accumulation of C<describe()> methods is hierarchical, and
1845dynamic in nature. That is, each class only sees those cumulative
1846methods that are defined in its own package or in one of its ancestors.
1847So calling the same C<describe()> on a base class object:
1848
1849    my $wax
1850        = Wax::Floor->new({ name=>'Shimmer ', patent=>1562516251 });
1851
1852    $wax->describe();
1853
1854only invokes the corresponding cumulative methods from that point on up
1855the hierarchy, and hence only prints:
1856
1857    The floor wax Shimmer (patent: 1562516251)
1858
1859Cumulative methods also accumulate their return values. In a list
1860context, they return a (flattened) list that accumulates the lists
1861returned by each individual method invoked.
1862
1863In a scalar context, a set of cumulative methods returns an object that,
1864in a string context, concatenates individual scalar returns to produce a
1865single string. When used as an array reference that same scalar-context-return
1866object acts like an array of the list context values. When used as a hash
1867reference, the object acts like a hash whose keys are the classnames from the
1868object's hierarchy, and whose corresponding values are the return values of
1869the cumulative method from that class.
1870
1871For example, if the classes each have a cumulative method that returns
1872their list of sales features:
1873
1874    package Wax::Floor;
1875    use Class::Std;
1876    {
1877        sub feature_list :CUMULATIVE {
1878            return ('Long-lasting', 'Non-toxic', 'Polymer-based');
1879        }
1880    }
1881
1882    package Topping::Dessert;
1883    use Class::Std;
1884    {
1885        sub feature_list :CUMULATIVE {
1886            return ('Low-carb', 'Non-dairy', 'Sugar-free');
1887        }
1888    }
1889
1890    package Shimmer;
1891    use Class::Std;
1892    use base qw( Wax::Floor  Topping::Dessert );
1893    {
1894        sub feature_list :CUMULATIVE {
1895            return ('Multi-purpose', 'Time-saving', 'Easy-to-use');
1896        }
1897    }
1898
1899then calling feature_list() in a list context:
1900
1901    my @features = Shimmer->feature_list();
1902    print "Shimmer is the @features alternative!\n";
1903
1904would produce a concatenated list of features, which could then be
1905interpolated into a suitable sales-pitch:
1906
1907    Shimmer is the Multi-purpose Time-saving Easy-to-use
1908    Long-lasting Non-toxic Polymer-based Low-carb Non-dairy
1909    Sugar-free alternative!
1910
1911It's also possible to specify a set of cumulative methods that
1912start at the base class(es) of the hierarchy and work downwards, the way
1913BUILD() does. To get that effect, you simply mark each method with
1914:CUMULATIVE(BASE FIRST), instead of just :CUMULATIVE. For example:
1915
1916    package Wax::Floor;
1917    use Class::Std;
1918    {
1919        sub active_ingredients :CUMULATIVE(BASE FIRST) {
1920            return "\tparadichlorobenzene, cyanoacrylate, peanuts\n";
1921        }
1922    }
1923
1924    package Topping::Dessert;
1925    use Class::Std;
1926    {
1927        sub active_ingredients :CUMULATIVE(BASE FIRST) {
1928            return "\tsodium hypochlorite, isobutyl ketone, ethylene glycol\n";
1929        }
1930    }
1931
1932    package Shimmer;
1933    use Class::Std;
1934    use base qw( Wax::Floor  Topping::Dessert );
1935
1936    {
1937        sub active_ingredients :CUMULATIVE(BASE FIRST) {
1938            return "\taromatic hydrocarbons, xylene, methyl mercaptan\n";
1939        }
1940    }
1941
1942So a scalar-context call to active_ingredients():
1943
1944    my $ingredients = Shimmer->active_ingredients();
1945    print "May contain trace amounts of:\n$ingredients";
1946
1947would start in the base classes and work downwards, concatenating base-
1948class ingredients before those of the derived class, to produce:
1949
1950    May contain trace amounts of:
1951        paradichlorobenzene, cyanoacrylate, peanuts
1952        sodium hypochlorite, isobutyl ketone, ethylene glycol
1953        aromatic hydrocarbons, xylene, methyl mercaptan
1954
1955Or, you could treat the return value as a hash:
1956
1957    print Data::Dumper::Dumper \%{$ingredients};
1958
1959and see which ingredients came from where:
1960
1961    $VAR1 = {
1962       'Shimmer'
1963            => 'aromatic hydrocarbons, xylene, methyl mercaptan',
1964
1965       'Topping::Dessert'
1966            => 'sodium hypochlorite, isobutyl ketone, ethylene glycol',
1967
1968        'Wax::Floor'
1969            => 'Wax: paradichlorobenzene,  hydrogen peroxide, cyanoacrylate',
1970    };
1971
1972Note that you can't specify both C<:CUMULATIVE> and C<:CUMULATIVE(BASE
1973FIRST)> on methods of the same name in the same hierarchy. The resulting
1974set of methods would have no well-defined invocation order, so
1975Class::Std throws a compile-time exception instead.
1976
1977
1978=item C<:STRINGIFY>
1979
1980If you define a method and add the C<:STRINGIFY> marker then that method
1981is used whenever an object of the corresponding class needs to be
1982coerced to a string. In other words, instead of:
1983
1984    # Convert object to a string...
1985    sub as_str {
1986        ...
1987    }
1988
1989    # Convert object to a string automatically in string contexts...
1990    use overload (
1991        q{""}    => 'as_str',
1992        fallback => 1,
1993    );
1994
1995you can just write:
1996
1997    # Convert object to a string (automatically in string contexts)...
1998    sub as_str : STRINGIFY {
1999        ...
2000    }
2001
2002
2003=item C<:NUMERIFY>
2004
2005If you define a method and add the C<:NUMERIFY> marker then that method
2006is used whenever an object of the corresponding class needs to be
2007coerced to a number. In other words, instead of:
2008
2009    # Convert object to a number...
2010    sub as_num {
2011        ...
2012    }
2013
2014    # Convert object to a string automatically in string contexts...
2015    use overload (
2016        q{0+}    => 'as_num',
2017        fallback => 1,
2018    );
2019
2020you can just write:
2021
2022    # Convert object to a number (automatically in numeric contexts)...
2023    sub as_num : NUMERIFY {
2024        ...
2025    }
2026
2027
2028=item C<:BOOLIFY>
2029
2030If you define a method and add the C<:BOOLIFY> marker then that method
2031is used whenever an object of the corresponding class needs to be
2032coerced to a boolean value. In other words, instead of:
2033
2034    # Convert object to a boolean...
2035    sub as_bool {
2036        ...
2037    }
2038
2039    # Convert object to a boolean automatically in boolean contexts...
2040    use overload (
2041        q{bool}    => 'as_bool',
2042        fallback => 1,
2043    );
2044
2045you can just write:
2046
2047    # Convert object to a boolean (automatically in boolean contexts)...
2048    sub as_bool : BOOLIFY {
2049        ...
2050    }
2051
2052
2053=item C<:SCALARIFY>
2054
2055=item C<:ARRAYIFY>
2056
2057=item C<:HASHIFY>
2058
2059=item C<:GLOBIFY>
2060
2061=item C<:CODIFY>
2062
2063If a method is defined with one of these markers, then it is automatically
2064called whenever an object of that class is treated as a reference of the
2065corresponding type.
2066
2067For example, instead of:
2068
2069    sub as_hash {
2070        my ($self) = @_;
2071
2072        return {
2073            age      => $age_of{ident $self},
2074            shoesize => $shoe_of{ident $self},
2075        };
2076    }
2077
2078    use overload (
2079        '%{}'    => 'as_hash',
2080        fallback => 1,
2081    );
2082
2083you can just write:
2084
2085    sub as_hash : HASHIFY {
2086        my ($self) = @_;
2087
2088        return {
2089            age      => $age_of{ident $self},
2090            shoesize => $shoe_of{ident $self},
2091        };
2092    }
2093
2094Likewise for methods that allow an object to be treated as a scalar
2095reference (C<:SCALARIFY>), a array reference (C<:ARRAYIFY>), a
2096subroutine reference (C<:CODIFY>), or a typeglob reference
2097(C<:GLOBIFY>).
2098
2099=back
2100
2101
2102=head1 DIAGNOSTICS
2103
2104=over
2105
2106=item Can't find class %s
2107
2108You tried to call the Class::Std::new() constructor on a class
2109that isn't built using Class::Std. Did you forget to write C<use Class::Std>
2110after the package declaration?
2111
2112=item Argument to %s->new() must be hash reference
2113
2114The constructors created by Class::Std require all initializer values
2115to be passed in a hash, but you passed something that wasn't a hash.
2116Put your constructor arguments in a hash.
2117
2118=item Missing initializer label for %s: %s
2119
2120You specified that one or more attributes had initializer values (using the
2121C<init> argument inside the attribute's C<ATTR> marker), but then failed
2122to pass in the corresponding initialization value. Often this happens because
2123the initialization value I<was> passed, but the key specifying the
2124attribute name was misspelled.
2125
2126=item Can't make anonymous subroutine cumulative
2127
2128You attempted to use the C<:CUMULATIVE> marker on an anonymous subroutine.
2129But that marker can only be applied to the named methods of a class. Convert
2130the anonymous subroutine to a named subroutine, or find some other way to
2131make it interoperate with other methods.
2132
2133=item Conflicting definitions for cumulative method: %s
2134
2135You defined a C<:CUMULATIVE> and a C<:CUMULATIVE(BASE FIRST)> method of the
2136same name in two classes within the same hierarchy. Since methods can only be
2137called going strictly up through the hierarchy or going strictly down
2138through the hierarchy, specifying both directions is obviously a mistake.
2139Either rename one of the methods, or decide whether they should accumulate
2140upwards or downwards.
2141
2142=item Missing new value in call to 'set_%s' method
2143
2144You called an attribute setter method without providing a new value
2145for the attribute. Often this happens because you passed an array that
2146happened to be empty. Make sure you pass an actual value.
2147
2148=item Can't locate %s method "%s" via package %s
2149
2150You attempted to call a method on an object but no such method is defined
2151anywhere in the object's class hierarchy. Did you misspell the method name, or
2152perhaps misunderstand which class the object belongs to?
2153
2154=item %s method %s declared but not defined
2155
2156A method was declared with a C<:RESTRICTED> or C<:PRIVATE>, like so:
2157
2158    sub foo :RESTRICTED;
2159    sub bar :PRIVATE;
2160
2161But the actual subroutine was not defined by the end of the compilation
2162phase, when the module needed it so it could be rewritten to restrict or
2163privatize it.
2164
2165
2166=item Can't call restricted method %s from class %s
2167
2168The specified method was declared with a C<:RESTRICTED> marker but
2169subsequently called from outside its class hierarchy. Did you call the
2170wrong method, or the right method from the wrong place?
2171
2172
2173=item Can't call private method %s from class %s
2174
2175The specified method was declared with a C<:PRIVATE> marker but
2176subsequently called from outside its own class. Did you call the wrong
2177method, or the right method from the wrong place?
2178
2179
2180=item Internal error: %s
2181
2182Your code is okay, but it uncovered a bug in the Class::Std module.
2183L<BUGS AND LIMITATIONS> explains how to report the problem.
2184
2185=back
2186
2187
2188=head1 CONFIGURATION AND ENVIRONMENT
2189
2190Class::Std requires no configuration files or environment variables.
2191
2192
2193=head1 DEPENDENCIES
2194
2195Class::Std depends on the following modules:
2196
2197=over
2198
2199=item *
2200
2201version
2202
2203=item *
2204
2205Scalar::Util
2206
2207=item *
2208
2209Data::Dumper
2210
2211=back
2212
2213
2214=head1 INCOMPATIBILITIES
2215
2216Incompatible with the Attribute::Handlers module, since both define
2217meta-attributes named :ATTR.
2218
2219
2220=head1 BUGS AND LIMITATIONS
2221
2222=over
2223
2224=item *
2225
2226Does not handle threading (including C<fork()> under Windows).
2227
2228=item *
2229
2230C<:ATTR> declarations must all be on the same line (due to a limitation in
2231Perl itself).
2232
2233=item *
2234
2235C<:ATTR> declarations cannot include variables, since these are not
2236interpolated into the declaration (a limitation in Perl itself).
2237
2238=back
2239
2240Please report any bugs or feature requests to
2241C<bug-class-std@rt.cpan.org>, or through the web interface at
2242L<http://rt.cpan.org>.
2243
2244
2245=head1 ALTERNATIVES
2246
2247Inside-out objects are gaining in popularity and there are now many other
2248modules that implement frameworks for building inside-out classes. These
2249include:
2250
2251=over
2252
2253=item Object::InsideOut
2254
2255Array-based objects, with support for threading. Many excellent features
2256(especially thread-safety), but slightly less secure than Class::Std,
2257due to non-encapsulation of attribute data addressing.
2258
2259=item Class::InsideOut
2260
2261A minimalist approach to building inside-out classes.
2262
2263=item Lexical::Attributes
2264
2265Uses source filters to provide a near-Perl 6 approach to declaring inside-out
2266classes.
2267
2268=item Class::Std::Storable
2269
2270Adds serialization/deserialization to Class::Std.
2271
2272=back
2273
2274=head1 AUTHOR
2275
2276Damian Conway  C<< <DCONWAY@cpan.org> >>
2277
2278
2279=head1 LICENCE AND COPYRIGHT
2280
2281Copyright (c) 2005, Damian Conway C<< <DCONWAY@cpan.org> >>. All rights reserved.
2282
2283Portions of the documentation from "Perl Best Practices" copyright (c)
22842005 by O'Reilly Media, Inc. and reprinted with permission.
2285
2286This module is free software; you can redistribute it and/or
2287modify it under the same terms as Perl itself.
2288
2289
2290=head1 DISCLAIMER OF WARRANTY
2291
2292BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
2293FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
2294OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
2295PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
2296EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2297WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
2298ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
2299YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
2300NECESSARY SERVICING, REPAIR, OR CORRECTION.
2301
2302IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
2303WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
2304REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
2305LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
2306OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
2307THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
2308RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
2309FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
2310SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
2311SUCH DAMAGES.
2312
2313
2314