From: Doug MacEachern Date: Sat, 5 Apr 1997 15:24:43 +0000 (-0500) Subject: Document sample function perl_eval() X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=8f1832628ef5654922d1b8e5959e65894d09ac5d;p=p5sagit%2Fp5-mst-13.2.git Document sample function perl_eval() Tim, your comments have changed perl_eval() from a quick & dirty example to something I'd like to see part of the Perl API, maybe called perl_eval_pv though. p5p-msgid: 199704051524.KAA06090@postman.osf.org --- diff --git a/pod/perlcall.pod b/pod/perlcall.pod index 0bfd142..85e0237 100644 --- a/pod/perlcall.pod +++ b/pod/perlcall.pod @@ -1915,6 +1915,44 @@ refers to the last. =back +=head2 Creating and calling an anonymous subroutine in C + +As we've already shown, L can be used to invoke an +anonymous subroutine. However, our example showed how Perl script +invoking an XSUB to preform this operation. Let's see how it can be +done inside our C code: + + SV *perl_eval(char *string, int croak_on_error) + { + dSP; + SV *sv = newSVpv(string,0); + + PUSHMARK(sp); + perl_eval_sv(sv, G_SCALAR); + SvREFCNT_dec(sv); + + SPAGAIN; + sv = POPs; + PUTBACK; + + if (croak_on_error && SvTRUE(GvSV(errgv))) + croak(SvPV(GvSV(errgv),na)); + + return sv; + } + + ... + + SV *cvrv = perl_eval("sub { print 'You will not find me cluttering any namespace!' }", TRUE); + + ... + + perl_call_sv(cvrv, G_VOID|G_NOARGS); + +L is used to compile the anonymous subroutine, which can +then be POPed off the stack. Once this code reference is in hand, it +can be mixed in with all the previous examples we've shown. + =head1 SEE ALSO L, L, L diff --git a/pod/perlembed.pod b/pod/perlembed.pod index 9111be1..9e3fb52 100644 --- a/pod/perlembed.pod +++ b/pod/perlembed.pod @@ -326,6 +326,36 @@ I to create a string: a = 9.859600 a = Just Another Perl Hacker +In the example above, we've created a global variable to temporarily +store the computed value of our eval'd expression. It is also +possible and in most cases a better strategy to fetch the return value +from L instead. Example: + + SV *perl_eval(char *string, int croak_on_error) + { + dSP; + SV *sv = newSVpv(string,0); + + PUSHMARK(sp); + perl_eval_sv(sv, G_SCALAR); + SvREFCNT_dec(sv); + + SPAGAIN; + sv = POPs; + PUTBACK; + + if (croak_on_error && SvTRUE(GvSV(errgv))) + croak(SvPV(GvSV(errgv),na)); + + return sv; + } + ... + SV *val = perl_eval("reverse 'rekcaH lreP rehtonA tsuJ'", TRUE); + printf("%s\n", SvPV(val,na)); + ... + +This way, we avoid namespace pollution by not creating global +variables and we've simplified our code as well. =head2 Performing Perl pattern matches and substitutions from your C program