
my $DEBUG = 1;

DEBUG::please_debug('foo') if $DEBUG;

sub foo {
  print "I LIKE PIE.  \n";
  return $_[0] + $_[1];
}

foo(3,4,5);
print foo(7,9), "\n";

package DEBUG;

my %orig;

sub please_debug {
  my $caller = caller;
  my $sub = shift;
  my $stub = sub { print STDERR "Calling $sub(@_)\n";
                   if (wantarray) {
                     my @r = $orig{$sub}->(@_);
                     local $" = ')(';
                     print STDERR " List context result: (@r)\n";
                     @r;
                   } else {
                     my $r = $orig{$sub}->(@_);
                     print STDERR " Scalar context result: ($r)\n";
                     $r;
                   }
                 };
  if (ref $sub) {
    $orig{$sub} = $sub;
  } else {
    $sub = join '::', $caller, $sub unless $sub =~ /::/;
    no strict 'refs';
    $orig{$sub} = \&{$sub};
    *$sub = $stub;
  }
  return $stub;
}

