Chapter 8
Of course, just like SvREFCNT, sv_2mortal() isn't just for SVs. You can mortalize 
anything you can cast to an SV*:
AV *av = (AV *) sv_2mortal((SV *) newAV()); // create a mortal AV
HV *hv = (HV *) sv_2mortal((SV *) newHV()); // create a mortal HV
There are also two constructor versions just for SVs that come in handy 
occasionally:
SV *mort_sv  = sv_newmortal();    // create an empty mortal SV
SV *mort_sv2 = sv_mortalcopy(sv); // create a mortal clone of sv
CAUTION Be careful never to mortalize an object twice accidentally. 
This will result in SvREFCNT_dec being called twice, with possibly disas 
trous results.
So, if mortalizing an SV (or AV, HV, and so on) schedules it for a SvREFCNT_dec at 
the end of the current scope, when does that happen? The answer is not what you 
might expect. In Perl, a scope ends at the next } in the code:
{        # scope start
  my $a;
}         # scope end
In C, things are a little more verbose:
ENTER; SAVETMPS;                      // start a new scope
SV *sv = sv_2mortal(newSVpv("foo",0); // create a mortal variable
FREETMPS; LEAVE;                      // end a scope, freeing mortal
                                      // variables with SvREFCNT == 1
Using the ENTER and SAVETMPS macros, you can start a new scope roughly the same 
way the Perl interpreter does. Then you can close the scope with FREETMPS and 
LEAVE. This triggers a SvREFCNT_dec on all variables mortalized inside the scope. The 
exact mechanics of Perl scopes are outside the reach of this chapter; for more 
details, see the perlguts documentation that comes with Perl.
It is worth noting that it is rarely necessary to create new scopes in C modules 
just to manage memory. This is because you can usually trust the Perl code calling 
your module to contain a scope when calling your code. You can usually mortalize 
196






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

web hosting perl

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Inexpensive Web Hosting  Jsp Web Hosting

Cheapest Web Hosting Jsp Hosting Cheap Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved