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

Monkies,

In a test I don't want to call the real subroutine for something, so I am overwriting the subroutine. I was hoping there would be a way to locally redefine the sub, but can't think of one. The following code works, but is a bit of a kludge. Is there a better way?

sub Foo::new { require MockFoo; return MockFoo->new(); } # blah blah blah - tests in here eval `cat Foo.pm`; # borrowed from 'Programming Perl' # to reestablish the original meaning

Replies are listed 'Best First'.
Re: locally redefining subroutine in module
by Corion (Patriarch) on Jun 30, 2004 at 10:09 UTC

    There is a much cleaner and easier way:

    { local *Foo::new = sub { require MockFoo; return MockFoo->new; }; ... tests ... }; # Foo::new is restored to its old value
      Thanks, Corion. Also: local *Foo::new = *MockFoo::new;. Dunno why I hadn't tried that..
Re: locally redefining subroutine in module
by adrianh (Chancellor) on Jun 30, 2004 at 10:19 UTC
      So you're telling me that as well as being ignorant of perl, I am also useless at searching. :)