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

1

8

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
Soraya answered 22/11, 2016 at 21:7 Comment(2)
So you want to mock the read, is that correct?Ligature
Perl always passes by reference, so all you have to do is modify $_[1].Yeryerevan
K
9

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';
Kassa answered 22/11, 2016 at 21:21 Comment(1)
Haha, I really out-thought myself there. Thanks!Soraya

© 2022 - 2024 — McMap. All rights reserved.