Tom said:
I'm not the best person to be giving an explanation at this level but I
think I understand where your confusion arises. I often see written
something like "a scalar (such as $x) is represented in Perl as a C
structure of type SV". (This statement equates a perl scalar to an SV.) I
would prefer to see it written as "a scalar (such as $x) is represented in
Perl as a pointer to a C structure of type SV". (This statement equates a
perl scalar to an SV*.)
When you pass a scalar to a function at the perl level, what's actually
happening at the C level ? You're passing a pointer to an SV structure to
the function.
Do you have a C compiler ? If you do, then here's a little Inline::C demo
you could run:
use warnings;
use Devel:
eek;
use Inline C => <<'EOC';
void foo(SV * x) {
printf("%x\n", x);
}
EOC
# Start perl code
$z = 17;
Dump($z);
print"#########\n";
foo($z);
__END__
For me that produces:
SV = IV(0x89dab4) at 0x3f5d3c
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 17
#########
3f5d3c
Note that at the C level, foo() receives an argument of type SV* - ie a
pointer to an SV structure.
And at the perl level foo() takes a simple scalar as its argument - ie $z.
Note also that the value output by foo() matches the address of the SV
structure. That's not a coincidence
So ... when I'm calling foo($z), the baggage is staying put. All I'm really
passing is a pointer to all of that baggage.
In a similar fashion, we can create a perl scalar at the C level.
use warnings;
use Devel:
eek;
use Inline C => <<'EOC';
SV * foo() {
SV * x;
x = newSViv(17);
return x;
}
EOC
$z = foo();
Dump($z);
__END__
That produces output of:
SV = IV(0xb492e8) at 0x3f5d3c
REFCNT = 1
FLAGS = (IOK,pIOK)
IV = 17
At the C level, an SV structure has been created, and a pointer to that
structure (an SV*) has been returned. Yet as far as perl is concerned, the
foo() function has returned a scalar variable.
Hth. (More importantly, I hope it's accurate. If not, I'm sure that someone
will correct it as needed.)
Cheers,
Rob