Examples
Let
us now write some code to see this API in action. Suppose you have a
Perl script, search.pl, containing subroutine
search_files
, defined in Example 19.1.
Example 19-1. search.pl
# search_files - a simple grep. Called as ... # search_files ("struct", "*.h") sub search_files { my ($pattern, $filepattern) = @_; local (@ARGV) = glob($filepattern); return unless (@ARGV); while (<>) { # Can do this because @ARGV has been primed if (/$pattern/o) { print "$ARGV\[$.\]: $_"; # File, line number, match line } } }
search_files
takes two string parameters and
returns nothing. There are several ways of calling this procedure
from C. Let’s start with
perl_call_argv()
, since it takes string arguments. The
piece of code in Example 19.2 searches for the word
“struct” in all C header files.
Example 19-2. ex.c: Embedding Perl
#include <EXTERN.h> #include <perl.h> static PerlInterpreter *my_perl; main(int argc, char **argv, char **env) { char *my_argv[] = {"struct", "*.h", NULL}; my_perl = perl_alloc(); perl_construct(my_perl); perl_parse(my_perl, NULL, argc, argv, env); perl_call_argv("search_files", G_DISCARD, my_argv); perl_destruct(my_perl); perl_free(my_perl); }
By passing NULL
instead of
xs_init
, we indicate to
perl_parse
that we are not interested in loading
any extensions. In addition, instead of calling
perl_run
, we call search_files
using perl_call_argv
(with the
G_DISCARD
flag to tell it to discard all returned results). This is how I compile and link this code on a Linux box: ...
Get Advanced Perl Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.