rpg has asked for the wisdom of the Perl Monks concerning the following question:

I have a perl module implemented using Attribute::Handler
package FOO; use strict; use warnings; use Attribute::Handlers; use base 'Exporter'; our @EXPORT = qw(__RETRY); sub __RETRY : ATTR(CODE) { my ($pkg, $sym, $code) = @_; no warnings 'redefine'; *{ $sym } = sub { my $self = $_[0]; my $result; print ("Executing subroutine\n"); $result = $code->(); if ($result) { print "You Pass\n"; } else { print "You Fail\n"; } } } sub foo : __RETRY { print "Executing Foo\n"; return 1; } 1;
Now when I call this module using require, and call function foo(), it executes only the foo's print statement.
require "FOO.pm"; FOO->import(); FOO::foo();
Output:
Executing Foo
But then I do the same using use, it does the correct job.
use FOO; FOO::foo();
Output:
Executing subroutine Executing Foo You Pass
Actually, in my code I am calling it using require and it's not working. Your help will be highly appreciated!!

Replies are listed 'Best First'.
Re: Attribute::Handler's behaviors with use vs require (optimization)
by tye (Sage) on Jul 10, 2012 at 17:46 UTC

    You are using attributes to replace a subroutine with a wrapper. If you compile code that calls the subroutine, then Perl optimizes the looking up of the code to call at the time the code is compiled and so that code doesn't notice when you replace the symbol table entry with your wrapper.

    So you need to replace the sub with the wrapper before you compile code that will call the sub.

    - tye        

Re: Attribute::Handler's behaviors with use vs require
by Athanasius (Archbishop) on Jul 10, 2012 at 14:31 UTC
    BEGIN { require 'FOO.pm'; FOO->import(); } FOO::foo();

    Output:

    Executing subroutine Executing Foo You Pass

    as required.

    HTH,

    Athanasius <°(((><contra mundum

      Yes, thanks for the reply. But for me this require statement is in an eval statement.