in reply to How is this Perl?

As I understand it, attributes are syntactic sugar to do "stuff". Here's a random simple example:

package Loud; use Attribute::Handlers; sub Loud :ATTR { my ($package, $symbol, $referent, $attr, $data, $phase) = @_; no strict 'refs'; # redefines subroutines given the "Loud" attribute *{$package.'::'.*{$symbol}{NAME}} = sub { # dup STDOUT and instead pipe things to another program open my $oldout, ">&STDOUT" or die "Can't dup STDOUT: +$!"; open STDOUT, "| perl -pe 'tr/a-z/A-Z/'" or die "Can't redirect STD +OUT: $!"; $| = 1; # call the original subroutine $referent->(@_); # restore STDOUT close STDOUT; open STDOUT, ">&", $oldout or die "Can't dup \$oldout: $!"; } } # ... in another file or package package main; use base qw/Loud/; # We want this function to be loud sub foo : Loud { print "Purple is a nice color.\n"; } foo(); print "Don't yell!\n";

The output of this program (it runs as shown above) is:

PURPLE IS A NICE COLOR. Don't yell!

Catalyst uses the ActionClass attribute here to append some action (provided by RenderView.pm) to your subroutine

Good Day,
    Dean

Replies are listed 'Best First'.
Re^2: How is this Perl?
by Anonymous Monk on Aug 11, 2007 at 23:42 UTC
    Is this like 'advice' in Lisp?

      Yeah, looks like it, though perl attributes can also be set on variables. Attributes may also be a bit more general/low-level since you get to (have to) perform your own function wrapping.

      Good Day,
          Dean

Re^2: How is this Perl?
by DJ Purrperl (Novice) on Aug 13, 2007 at 23:07 UTC
    Thank you very much! This was indeed educational. Living and learning. I do wish Perl would keep it simple, and not introduce too many esoteric constructs like this one. Let's stay true to the "P" in Perl!
      I do wish Perl would keep it simple...

      That depends on your definition of simplicity. Attributes offer amazing opportunities to simplify interfaces. Look at P5NCI::Declare for an example.