perlmockingmod-perl2

in perl how to write to caller's variable without using XS?


I'm writing unit tests around some old code, and find the need to write a mock around Apache2::Request's read() method

my $r = Apache2::Request->new(...);

$r->read(my $buf, $len);

Is there a way to write a function in Perl to populate $buf? I'm pretty sure the only way to do that is from XS code with a **, but I thought I'd at least ask first.

Using Apache2::Request directly leads to this, hence my desire to mock it.

perl: symbol lookup error: .../APR/Request/Apache2/Apache2.so: 
undefined symbol: modperl_xs_sv2request_rec

Solution

  • In a Perl subroutine or method, parameters are passed via the @_ array. Elements in this array are aliases for the variables in the calling sub.

    The common way of unpacking @_ is by making a copy like this:

    my($self, $buf, $len) = @_;
    

    So assigning to $buf in this case won't work because you've only modified your copy of the variable. But if you directly modify the value in @_ then that will affect the caller's variable:

    $_[1] = 'some data';