Using Perl in Php

Embed Size (px)

Citation preview

  • 7/28/2019 Using Perl in Php

    1/9

    Using Perl Code from PHPDmitry Stogov | 8 comments | Wednesday, April 14, 2004

    Intended AudienceIntroductionPerl Interpreter in PHPUsing Perl ObjectsError HandlingSummary

    Intended Audience

    This article describes the perl extension for PHP. It is intended for developers who use bothlanguages in their projects, or who are migrating from one language to the other. It could be of

    general interest to other developers.

    Introduction

    PHP and perl are two very popular Web programming languages. They both have many librariesand extensions that can simplify the process of development, but often you can find a perl libraryyou want, and not the corresponding library in PHP. (Perl is older then PHP, so naturally it has alarger selection of libraries and extensions.) This was the main reason that the perl extension forPHP was written.

    Many large projects use both PHP and perl, with some subsystems implemented in PHP, and othersin perl. Often these subsystems need to communicate with each other, and some perl modules - suchas PHP::Include and PHP::Session - have been implemented to achieve this (seehttp://www.cpan.org/modules/by-module/PHP/ for more information). However, although theyallow PHP session files to be read, PHP variables to be serialized and simple PHP code to beexecuted from within perl, there is no real communication between the two interpreters.

    The PHP perl extension was implemented to allow the usage of perl code from within PHP. It is awrapper that embeds the perl interpreter and converts data from PHP to perl and back. At the timeof writing it only provides a one-way interface from PHP to perl, but in the future it could beextended to implement a full two-way interface. The perl extension allows the programmer to dothe following from a PHP script:

    load and execute perl files

    evaluate perl code

    access perl variables

    call perl functions

    instantiate perl objects

    access properties of perl objects

    call methods of perl objects

    All these features are accessible through a single API class called Perl.

    PHP's perl extension is available from the PECL web site at http://pecl.php.net/package/perl . Thelatest development version can be obtained with the following CVS command:

    $ cvs -d :pserver:cvs.php.net:/repository co pecl/perl

    If you have a full perl installation, the extension will work with it. If you don't have perl on board,

    http://devzone.zend.com/member/83-Dmitry-Stogovhttp://devzone.zend.com/article/1712#commentshttp://devzone.zend.com/article/1712#Heading1http://devzone.zend.com/article/1712#Heading2http://devzone.zend.com/article/1712#Heading3http://devzone.zend.com/article/1712#Heading4http://devzone.zend.com/article/1712#Heading5http://devzone.zend.com/article/1712#Heading6http://www.cpan.org/modules/by-module/PHP/http://pecl.php.net/package/perlhttp://devzone.zend.com/article/1712#commentshttp://devzone.zend.com/article/1712#Heading1http://devzone.zend.com/article/1712#Heading2http://devzone.zend.com/article/1712#Heading3http://devzone.zend.com/article/1712#Heading4http://devzone.zend.com/article/1712#Heading5http://devzone.zend.com/article/1712#Heading6http://www.cpan.org/modules/by-module/PHP/http://pecl.php.net/package/perlhttp://devzone.zend.com/member/83-Dmitry-Stogov
  • 7/28/2019 Using Perl in Php

    2/9

    you can still communicate with the perl interpreter through PHP by putting a copy ofperl58.so orperl58.dllsomewhere PHP can find it (in the PHP directory or in your system path).

    Perl Interpreter in PHP

    To access the perl interpreter from PHP, you must first create an instance of the Perl class. Its

    constructor can receive some parameters, but we will omit them at this point. They are necessary forworking with perl objects, but not for working with the interpreter itself.

    $perl= newPerl();

    This line of code creates an instance of the perl interpreter. It is possible to create several instancesof the interpreter, but all of them will use the same one internally, so that all code and variables will

    be shared across instances. The object $perl can be used to execute external perl files, evaluate

    inline perl code, access perl variables and call perl functions.

    External perl files can be loaded using the Perl::require()method. Take a look at the

    following example:

    Example 1 (test1.pl)

    print "Hello from perl! "

    Example 1 (test1.php)

    In this example perl outputs a string directly to the PHP output stream, but in some cases you willwant to grab the output as a string and process it with your PHP code. This can be done using thePHP output buffering API:

    Example 2 (test2.php)

    As you can see, it works fine. Of course the same can be done with PHP's system call, but lessefficiently. The system() function will start the interpreter each time it's called, whereas $perl-

    >eval() uses the embedded interpreter in the same address space and doesn't need to create a newprocess.

    As was said earlier, the PHP perl extension can evaluate inline perl code. This method is more

    http://devzone.zend.com/article/'/manual/view/page/function.ob-start.html'http://devzone.zend.com/article/'/manual/view/page/function.require.html'http://devzone.zend.com/article/'/manual/view/page/function.ob-get-contents.html'http://devzone.zend.com/article/'/manual/view/page/function.ob-end-clean.html'http://devzone.zend.com/article/'/manual/view/page/function.print.html'http://devzone.zend.com/article/'/manual/view/page/function.ob-start.html'http://devzone.zend.com/article/'/manual/view/page/function.require.html'http://devzone.zend.com/article/'/manual/view/page/function.ob-get-contents.html'http://devzone.zend.com/article/'/manual/view/page/function.ob-end-clean.html'http://devzone.zend.com/article/'/manual/view/page/function.print.html'
  • 7/28/2019 Using Perl in Php

    3/9

    useful if you want to execute a small piece of code. With the Perl::eval()method you don't

    need to create several small perl files, but can instead simply embed perl code into PHP.

    Example 3 (test3.php)

  • 7/28/2019 Using Perl in Php

    4/9

    ["c"]=>NULL

    }*/

    ?>

    This example evaluates the same data - a list - in different contexts, and as you can see, there arethree different results from that data.

    Perl has several scopes of global variables (scalars $x, arrays @x, hashes %x and code &x). PHP's

    perl extension allows you to access global scalar, array and hash variables. To access scalar perlvariables, just use the property with the same name. To access array and hash variables, use thesame trick as for selecting the evaluation context.

    Example 5 (test5.php)

    As you see, here we have three variables with the same name but in different scopes, and of courseall three have different values.

    The perl extension allows not only reading but also writing to perl variables. You can do this by

    assigning a new value to the corresponding property; however, you cannot modify part of a perlarray or hash. (The modification will not take effect.)

    Evaluating perl variables is just one simple interaction between PHP and perl. More often we need

    http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'
  • 7/28/2019 Using Perl in Php

    5/9

    to call a single perl function. PHP's perl extension provides a simple and elegant way to do this. Youjust need to call the method with the corresponding name via the interpreter, and pass parameters toit:

    Example 6 (test6.php)

    The function can receive parameters and return a scalar or complex value. As with eval(), any

    function call can be made in one of three different contexts (scalar, array or hash), and the contextcan be specified in the same way.

    Perl uses packages to limit the name scope of variables and functions, and sometimes we need to

    call functions or access variables from these packages using qualified names. Such names doesn'tconfirm to PHP syntax, but they can be used with the special construct ->{}.

    Example 7 (test7.php)

  • 7/28/2019 Using Perl in Php

    6/9

    makemake testmake install

    at the command prompt. On Windows systems you will need to replace make with nmake;

    however, this will only work if you have MSVS tools installed.

    If you don't have a full perl installation - i.e. you're running perl as a shared object - it is stillpossible to run perl modules once they have been built elsewhere. The minimal environmentnecessary for running them consists of the entire set of perl package management (*.pm) files fromperllib, and the full perllibauto and perllibDigest directories.

    The PHP Perl extension cannot call internal perl functions (print, read, etc); you will need to

    use Perl::eval() in order to access these. For example, in order to include the minimal module

    environment outlined above you would need to call:

    $perl->eval("BEGIN {unshift( @INC, 'perlenv_dirpath'); }");

    Using Perl Objects

    In common with many other programming languages, perl uses an object-oriented approach, but ithas no special syntax for classes. Classes are simply packages that happen to provide methods todeal with objects; methods are simply package functions that expect an object reference as the firstargument; objects are simply references that 'know' which class they belong to.

    The perl extension allows you to instantiate perl objects from a PHP script, and to access theirproperties and methods. The same Perl class is used for this, but this time you need to pass

    arguments to its constructor. The first argument is a perl class (package) name, the second is theoptional constructor name, and any remaining arguments are constructor-specific. If the constructorname is omitted then the default constructornew is used.

    new Perl(string class_name [, string constructor_name [, mixedargs]]);

    The following example defines the perl class Point with two constructors, new and Point. The

    first constructor doesn't accept any special arguments; the second receives initial coordinate values.The class has two properties, x and y, and two methods, move() and get(). As you can see, the

    method move() moves a point to the offset specified in the arguments passed to it. The method

    get() is more interesting. Depending on the context, it returns the current coordinates as a string

    (in the scalar context) or as an array (in the array context).

    As with native PHP objects, you can call the methods of instantiated perl objects and access theirproperties. The only difference is the calling context. By default, methods are called in the scalar

    context. To call them in an array or hash context, use the same trick as before: the method shouldnot be called directly on the perl object, but on a special property (array or hash).

    All properties can be accessed directly (without the array or hash property). This is because perlobjects can contain only scalar properties. Arrays and hashes are represented as references to them,and references are scalars in perl. Object properties can be read, written, modified and evenundefined, but parts of a property cannot be modified. For example, we can't modify an element ofan array property.

    Example 8 (test8.php)

  • 7/28/2019 Using Perl in Php

    7/9

    $perl->eval('package Point;sub new {

    my $this = shift;my $type = ref($this) || $this;my $self = {};

    $self->{x} = 0;$self->{y} = 0;bless $self, $type;return $self;}

    sub Point {my $this = shift;my $type = ref($this) || $this;my $self = {};$self->{x} = shift;$self->{y} = shift;

    bless $self, $type;return $self;}

    sub move {my $self = shift;$self->{x} += shift;$self->{y} += shift;}

    sub get {my $self = shift;if (wantarray) {

    return ($self->{x}, $self->{y});} else {

    return $self->{x} . "x" . $self->{y};}

    }');

    // create perl object "Point" with constructor "new"$p1= newPerl("Point");var_dump($p1);$p1->x+=100; // modify property

    unset($p1->y); // undefine propertyvar_dump($p1);

    // create perl object "Point" with constructor "Point"$p2= newPerl("Point","Point",100,200);var_dump($p2);$p2->move(200,200); // call method "move"var_dump($p2->get()); // call method "get" in scalarcontextvar_dump($p2->array->get()); // call method "get" in arraycontext

    echo$p2->x.".".$p2->y." ";// print perl object properties

    ?>

    http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/unset.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/unset.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'
  • 7/28/2019 Using Perl in Php

    8/9

    Error handling

    The perl extension uses the PHP exception mechanism to report perl errors. A special exceptionclass, PerlException, is used for this. The following example tries to evaluate invalid perl

    code, and as a result Perl::eval() throws a PerlException:

    Example 9 (test9.php)

    Exceptions can be thrown by Perl::eval(), Perl::require(), or a call to a perl function,

    object method or constructor.

    Summary

    The PHP perl extension is a simple one-way binding from PHP to perl. It allows you to execute perlcode from PHP, and has the ability to access perl variables, call perl functions, and instantiate perlobjects.

    Note that the extension is still marked EXPERIMENTAL, so your ideas and suggestions can help tomake it stable and usable. Please report any problems you find with the extension tohttp://bugs.php.net/.

    [1] - Perl defines the scalar and array (list) contexts. The hash context is the same as the array (list)context, but the result is converted to an associative PHP array (hash array).

    Comments (Login to leave comments)Wednesday, March 28, 2007

    PHP4??6:22PM GMT omnoviatechThis PECL extension seems really cool, but its for PHP5 only. How can I do this php->perl stuff in

    php4?Wednesday, July 4, 2007RE: PHP4??5:21PM GMT Anonymous User [unregistered]

    You upgrade to php5. Its been out for 4 years, its time for an upgrade.Wednesday, September 26, 2007INSTALLED FINE, NOT WORKING

    http://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://bugs.php.net/http://devzone.zend.com/member/2685-omnoviatechhttp://devzone.zend.com/article/'/manual/view/page/function.var-dump.html'http://bugs.php.net/http://devzone.zend.com/member/2685-omnoviatech
  • 7/28/2019 Using Perl in Php

    9/9

    8:02PM GMT Robert Buzink [unregistered]I installed PHP's perl extension on debian. Everything installed without any errors. I checkedwhether PERL is properly installed by doing 'apt-get install perl'. To be completely sure, I copiedthe perl.so file in the usr/lib/php5 directory. When I try to use the extension within a php script($perl = new Perl();),I get a php error that the class cannot be found. Any ideas?Tuesday, April 22, 2008

    LOAD PERL.SO2:48PM GMT Ala'a Ibrahim [unregistered]addextention=perl.so to your php.ini fileMonday, June 2, 2008WHAT ABOUT USING ANOTHER PERL2:01PM GMT Anonymous User [unregistered]$perl = New Perl() points to /usr/bin/perl or what default perl is.What if I want to use /usr/local/bin/perl?

    Do I have to decide this at pecl compile time?

    Saturday, October 25, 2008

    PASSING VARIALBE FROM PHP TO PERL10:57AM GMT strahinjaI`m trying to pass variable from PHP file to perl script in code bellow. If someone has an exampleto post that would be great, btw. everything else works great.Sunday, January 25, 2009

    BUG((10:18PM GMT ssg0Do somebody know how to fix this bug?

    http://www.pecl.php.net/bugs/bug.php?id=14644Monday, May 18, 2009AVOIDING SENDING HEADER?10:36PM GMT Anonymous User [unregistered]Hello,I notice that doing a $perl->require() or $perl->eval(), will send the header even if using output

    buffering. Once that happens, I can no longer set cookies, etc. Has anyone been able to use perl

    without it sending a header?

    Thanks!

    http://devzone.zend.com/member/6341-strahinjahttp://devzone.zend.com/member/6834-ssg0http://devzone.zend.com/member/6341-strahinjahttp://devzone.zend.com/member/6834-ssg0