Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • The code sample you posted is almost there. You just need to create an anonymous package name instead of using __PACKAGE__. I would simply append the accessor names to the base class, e.g. Object::Anonymous_ding_wong_line

        sub new {
            my $class = shift;
            my %args = @_;
            my $self = { };
            my $name = join('_', $class, keys %args);

            for my $arg (keys %args) {
                # Store the given value
                $self->{$arg} = $args{$arg};

                # Create the accessor
                my $methname = $name . "::" . $arg;
                *{$methname} = sub {
                    my ($innerself) = @_;
                    return $innerself->{$arg};
                };
            }

            bless $self, $name;
        }

    You can use Class::MOP::Class as chromatic notes. Or here's a similar thing using Badger::Class [badgerpower.com]:

        package Class::Auto;

        use Badger;
        use Badger::Class 'class';

        sub new {
            my ($class, %self) = @_;
            my $name = join('_', $class, sort keys %self);
            class($name)->accessors(keys %self);
            bless \%self, $name;
        }

    And here's an example of use:

        use Class::Anon;

        my $object = Class::Anon->new(
            x => 10,
            y => 20,
            z => 30
        );

        print ref $object, "\n"; # Class::Anon_x_y_z
        print $object->x, "\n"; # 10
        print $object->y, "\n"; # 20
        print $object->z, "\n"; # 30

    • s/Auto/Anon/ # cut and paste fail

    • The code sample you posted is almost there. You just need to create an anonymous package name instead

      Ha! Who woulda' thunk? I wrote that example code off-the-cuff in an attempt to better explain what I wanted. But that's a simple enough change that I'm now tempted to start using it as-is. Any other issues you can think might be lurking in the code?