[Israel.pm] Uses for Attributes

Ran Eilam ran.eilam at gmail.com
Tue Mar 20 12:36:05 PDT 2007


> > I tried to show you some uses for it in my previous message. If we
> > take the writing a testing library as an example, I can mark the
> > functions that are directly used for test assertion with the ":
> > testfunc" attribute and then walk the caller() (
> > http://perldoc.perl.org/functions/caller.html ) stack backwards to
> > find the top function with this marker and then display the context
> > that it has. This beats Test::Builder's current method of doing local
> > $Test::Builder::Level = $Test::Builder::Level + 2;

Lovely example.

> In my testing framework, I do that by walking up the caller stack to
> the first function not inside the Test package. Simple enough, no?

Hey Jason! What's up in Rehovot?

Except you still need this Test package, or some other marker.

That's what an attribute is. Since packages are already used for other
purposes (e.g. class clustering), the  out-of-band-data that
attributes lets you inject into code is quite nice.

And attributes take parameters. So a test sub can specify- "run this
in less than 3 seconds", or "run this 3 times".

And then there are attributes on variables. I have seen it used to
mean that a scalar value is actually an object, which notifies when
the value changes (i.e. Smalltalk ValueModel):

my $value: Value;
$value = 1 + 2;
print $value;
$value++;

Which automatically ties it to a certain class, so it looks like a
scalar, but you can also listen to changes in it:

add_listener { print "new value: $_\n" }, $value;

Without attributes, you would have needed to export a constructor sub,
or expect the user to call tie() herself. Actually:

my $value = Value;

and

my $value: Value;

look almost the same. But the orthogonality of attributes help make
the 2nd better:

my $value = Value(666);

vs.

my $value: Value = 666;

Lot's of CPAN modules use attributes. Search Attributes.

And then of course there is the crazy side of CPAN: This Marcel dude
(original author of Aspect.pm BTW) wrote an attribute interface for
all Tie'd things on CPAN:

http://search.cpan.org/~marcel/Attribute-TieClasses-0.01/TieClasses.pm

Obsessive in a delightful way.

Ran



More information about the Perl mailing list