title: How to set a Perl environment variable from an XSUB?
body: <p>I am trying to set a Perl environment variable from an XSUB. I want it to take immediate effect before the XSUB exits. Here is my XS file, <code>Module.xs</code>:</p>
  
  <pre><code>#define PERL_NO_GET_CONTEXT
  #include "EXTERN.h"
  #include "perl.h"
  #include "XSUB.h"
  
  MODULE = My::Module  PACKAGE = My::Module
  PROTOTYPES: DISABLE
  
  void
  set_env_test()
      CODE:
          I32 croak_on_error = 1;
          eval_pv("$ENV{PERL_MEM_LOG}='ms'", croak_on_error);
          printf("C1: getenv : %s\n", getenv("PERL_MEM_LOG"));
          printf("C1: PerlEnv_getenv : %s\n", PerlEnv_getenv("PERL_MEM_LOG"));
          my_setenv("PERL_MEM_LOG", "s");
          printf("C2: getenv : %s\n", getenv("PERL_MEM_LOG"));
          printf("C2: PerlEnv_getenv : %s\n", PerlEnv_getenv("PERL_MEM_LOG"));
  </code></pre>
  
  <p>and here is a Perl script that uses the XSUB:</p>
  
  <pre><code>use feature qw(say);
  use strict;
  use warnings;
  use ExtUtils::testlib;
  use My::Module;
  
  {
      say "Before: ", get_env();
      My::Module::set_env_test();
      say "After: ", get_env();
  }
  
  sub get_env {
      if (exists $ENV{PERL_MEM_LOG}) {
          return $ENV{PERL_MEM_LOG};
      }
      else {
          return "undef";
      }
  }
  </code></pre>
  
  <p>The output is:</p>
  
  <pre><code>Before: undef
  C1: getenv : ms
  C1: PerlEnv_getenv : ms
  C2: getenv : s
  C2: PerlEnv_getenv : s
  After: ms
  </code></pre>
  
  <p>I would like to know if it is possible to set the environment variable without using <code>eval_pv()</code>? Is there a specific API function that I can use?</p>
  
  <p>Observations:</p>
  
  <ul>
  <li><code>eval_pv()</code> works as expected,</li>
  <li><code>my_setenv()</code> works locally and supersedes the value set by <code>eval_pv()</code> until the XSUB exits, then the old value is restored.</li>
  <li><code>my_setenv()</code> cannot be used to set the Perl environment variable permanently, its effect only lasts within the XSUB.</li>
  <li><code>getenv()</code> and <code>PerlEnv_getenv()</code> seems to do the same thing (?)</li>
  </ul>