Perl: How to create objects on the fly?

Viewed 5640

My goal is to be able to use $obj like this:

print $obj->hello() . $obj->{foo};

And I would like to create an object inline, maybe using something like this:

my $obj = (
    foo => 1,
    hello => sub { return 'world' }
);

but when I try to use $obj as an object, I get an error saying that $obj has not been blessed. Is there some base class (like stdClass in PHP) I can use to bless the hash so that I can use it as an object?


For those that know JavaScript, I am trying to do the following, but in Perl:

# JS CODE BELOW
var obj = { foo: 1, hello: function () { return 'world' } };
echo obj.hello() + obj.foo;
8 Answers
Related