2

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,

1
  • Despite from the question, the code shown seems rather useless. Is there a real-life application for it? A more typical usage would be: sub print_maker ($) { my $prefix = $_[0]; sub ($) { print $prefix, $_[0] }}. Then use my $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. Commented Apr 21, 2022 at 11:11

1 Answer 1

1

You are setting your global variable to a reference to some data created locally in the function.

In Perl (a "managed memory" language), this will be a reference counted "object" (using the term loosely, as it is a string here) that will not be garbage collected until all references go away.

In C, this is just a memory address and you have to make sure yourself that it remains valid (and does not point at stack space that is already reclaimed as soon as the function returned).

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @Thilo To make reference count available for my variables of a subroutine, does that mean the my variable will be stored in data segment if it is referenced? And stored in stack if it is not referenced?
I think all variables in Perl are allocated in the managed heap area, rather than an automatic stack. If the subroutine exits, the reference counts for all local variables will decrease, usually becoming zero unless you created another reference for it. This is like using objects in Java (as opposed to primitives, which can be stack-allocated and are more like in your C example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.