Forgot your password?
User Journal

rjw57's Journal: Sickness

Journal by rjw57

Well I've been playing with embedding Perl within C# and have managed to write the first 'useful' program. The following is a re-write of the LWP simple test program in C#.

namespace PerlEmbedExamples {
    using System;
    using Perl;

    class LWPExample {
        public static void Main(string[] args) {
            Console.WriteLine("Embedding Perl within Mono - LWP Example");
            Console.WriteLine("(C) 2004 Rich Wareham <>\n");

            Interpreter interpreter = new Perl.Interpreter();

            try {
                Scalar ua = interpreter.CallClassMethod("LWP::UserAgent", "new");
                interpreter.CallMethod(ua, "agent", "Mozilla/6.0");
                Scalar req = interpreter.CallClassMethod("HTTP::Request", "new",
                        "GET", "");
                Scalar res = interpreter.CallMethod(ua, "request", req);

                if(interpreter.CallMethod(res, "is_success")) {
                    Scalar content = interpreter.CallMethod(res, "content");

                    Console.WriteLine("Content:\n{0}", content);
                } else {
                    Console.WriteLine("Request failed.");
            } catch ( Exception e ) {
                Console.WriteLine("Error was thrown: {0}", e.Message);

You may well ask "Why bother?". Well actually I've been wanting to write some code in C# for a while but there just aren't enough utility libraries/classes about under sufficiently good licenses. I could do a load of P/Invoke magic to make use of C-libraries but that invoves a) recompiling on each platform and b) only using C-libraries available on multiple platforms. Using Perl gives C# immediate access to the vast wealth of modules on CPAN.

This makes wrapper classes around Perl modules pretty easy to implement :). Also the magic boxing and unboxing ability of C# means that I can use 'Scalar's pretty much just like 'Variants' in VB (which is more or less a good thing, I think).

"Most of us, when all is said and done, like what we like and make up reasons for it afterwards." -- Soren F. Petersen