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

use Perl Log In

Log In

[ Create a new account ]

revdiablo (1502)

revdiablo
  (email not shown publicly)

Journal of revdiablo (1502)

Tuesday September 15, 2009
05:44 PM

Anonymous objects as easily as hashrefs?

[ #39633 ]

Is there anything buried in the sea of Moose--or any object system on CPAN--that allows creating anonymous objects about as easily as creating anonymous hashrefs? I would be much happier using tiny objects to store structured data in my code, but the hashref syntax is just so darn convenient.

Here's an example of what I'd love to be able to do:

while (my $line = readline()) {
    my ($ding, $dong) = parse($line);

    next if $seen{$ding}++;

    push @dingfirsts, Object::Anonymous->new(
        ding => $ding,
        dong => $dong,
        line => $.,
    );
}

for (@dingfirsts) {
    say "First ", $_->ding, " on line ", $_->line;
}

Please ignore the obvious flaws in this contrived example. The most important part, to me, is that the object is defined by its constructor, and nowhere else. Methods would get created for any attributes given in the constructor.

Here's a quick implementation that may help explain what I'm after. There are some really obvious flaws that would prevent me from ever actually using this code--most significantly, it's modifying the Anonyject class at runtime, so it really isn't anonymous at all--but the mechanics are pretty close to what I'd want.

package Anonyject;

sub new {
    my $name = shift;
    my %args = @_;
    my $self = {};

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

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

    bless $self, $name;
}

package main;
use feature 'say';

my $obj1 = Anonyject->new(
    ding => "wing",
    dong => "wong",
    line => 23_939,
);
my $obj2 = Anonyject->new(
    something => "else",
);

say $obj1->ding;      # Says "wing"
say $obj2->something; # Says "else"

say $obj1->something; # Should break, but doesn't
say $obj1->broken;    # Breaks properly

So that's wishful thinking of the day. I'm hoping one of the popular object systems already does what I want, but maybe I can use Class::MOP to implement this properly. Any ideas would be lovely.

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.