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

#!/usr/bin/perl -w use strict; use Hook::LexWrap; sub get { return "Foo!" } wrap get, post => sub { warn $_[-1] }; get();
This code should print 'Foo! at wrap.pl line 7.', but instead, outputs:
Use of uninitialized value in warn at wrap.pl line 6. Warning: something's wrong at wrap.pl line 6.
Anyone know why?

---
"A Jedi uses the Force for knowledge and defense, never for attack."

Replies are listed 'Best First'.
Re: Hook::LexWrap doesn't capture return value of subroutine in post() wrapper
by Roger (Parson) on Dec 23, 2003 at 04:10 UTC
    Closer examination revealed that the value of @_ varies depending on how the function is called.
    #!/usr/bin/perl -w use strict; use Hook::LexWrap; use Data::Dumper; sub get { return "Foo!" } wrap get, post => sub { print Dumper(\@_) }; my @n = get(); my $n = get(); get();
    And the output -
    $VAR1 = [ [ 'Foo!' ] ]; $VAR1 = [ 'Foo!' ]; $VAR1 = [ bless( sub { "DUMMY" }, 'Hook::LexWrap::Cleanup' ) ];
    Looking at the documentation, the author states that:
    In a post-wrapper, $_[-1] contains the return value produced by the wrapped subroutine. In a scalar return context, this value is the scalar return value. In an list return context, this value is a reference to the array of return values. $_[-1] may be assigned to in a post-wrapper, and this changes the return value accordingly.
    What the author didn't mention is that in a void context, $_[-1] is the object. Thus giving you the error in 'warn'.