I have two code sections as below, in Perl and C. This is about Perl's my variables and C's automatic variables. To some extent, they are quite similar in that they get initialized every time entering the function. But Perl can reference my variables of a subroutine, C will get random value if doing so because the function call stack is destroyed after return. Anyone knows how Perl implements this feature? It couldn't be keeping every subroutine call stack untouched, is it that Perl allocates every my variable created in a subroutine in "data segment" (comparing to stack)?
Perl code:
use strict;
use warnings;
my $ref;
sub func
{
my $str = "hello";
$ref = \$str;
}
func;
print "value is ";
print "${$ref}\n";
C code:
#include <stdio.h>
int *pi;
void func(void)
{
int j = 9;
pi = &j;
}
int main(void)
{
func();
printf("value is ");
printf("%d\n", *pi);
return 0;
}
Thanks,
sub print_maker ($) { my $prefix = $_[0]; sub ($) { print $prefix, $_[0] }}. Then usemy $printer = print_maker('foobar: '); $printer->('some junk');You can't do that in C. "closures" is the mechanism you want to learn about, most likely.