In Murder of a Perl coder I commented that coding C# could be almost as much fun as coding Perl, at which point Jenda suggested that C# Regex support was vomit-inducing :)

I know there are a number of esteemed monks familiar with both Perl and C# so I thought it might be useful to open this discussion to a wider audience, especially since many Win32 monks can probably expect to face this comparison sooner or later, courtesy of the MS marketing juggernaut.

So here is a comparison of a tiny templating app, based on the fillTemplate sub written by Jenda, in both Perl and C#. Both of these are fully functional programs, you should be able to run them without any modification (although I've not tried the C# version with Mono).

Please draw your own conclusions, I'm not selling any here.

use strict; use warnings; my %hash = ( "a" => "abc", "d" => "def", "g" => "ghi" ); my $text = "%a% %d% %g%"; print "Before: $text\n"; print "After : ", fillTemplate($text, \%hash), "\n"; sub fillTemplate { my ($text, $hash) = @_; $text =~ s/%(\w)%/$hash->{$1}/g; return $text; }

C#

using System; using System.Collections; using System.Text.RegularExpressions; class test { static Hashtable hash = new Hashtable(); static void Main () { hash.Add("a", "abc"); hash.Add("d", "def"); hash.Add("g", "ghi"); string text = "%a% %d% %g%"; Console.WriteLine( "Before: {0}", text ); Console.WriteLine( "After : {0}", fillTemplate( text ) ); } static string fillTemplate ( string text ) { return Regex.Replace( text, @"%(?<templ>\w)%", new MatchEvaluator( hashLookup ) ); } static string hashLookup ( Match m ) { return (string)hash[m.Groups["templ"].Value]; } }

Notes on the C# version

 

Replies are listed 'Best First'.
Re: Comparing Perl with C#, a simple templating example
by perlcapt (Pilgrim) on Oct 17, 2004 at 11:58 UTC
    Your example is my first intro to C#. I probably won't live long enough to ever have to program in C# since I get to pick the languages that I use, but I can see a serious effort by MS to make something useful. To the 'C++' programmers, it is a natural extension to what they already know. But, I've never really trusted MS for their marketing and development plan. I hold some serious grudges with them for having intentionally gone after the destruction of non-proprietary (read "open") standards. They were doing this back when they first introduced their C-language compiler and libraries. They weren't alone in doing that. I criticized Borland for the same sin.

    It is hard to embrace a technology you don't trust.

      "I probably won't live long enough to ever have to program in C#"

      Try it at least once, at least I will ;-)

      As a matter of fact, one of our GUI user interface needs to be totally rewritten becaue of the user requirement changed. I am looking at C#, it was in Open Road (an engres thingy).

      BTW, for most of the application areas, C# is not targetting any thing else, but Java. GUI application is a good candidator to try C# with, because of the IDE. I took a look at the way C# defines event, handles event are quite interesting. C# even tries to beat Java with small things like how to define getters and setters.

      Perl should not be the one feels the most pressure from C#. For example, in this case, as a GUI interface thing, at least from my point of view, Perl is not a candidator any way.

        C# even tries to beat Java with small things like how to define getter +s and setters.
        Thats just syntactic sugar. You may be able to use "properties" but in essence they just get re-written to the underlying subroutines anyway. Of course if you use code completion incorrectly you can get bitten :). Here's some recursive property code just for fun.
        using System; public class MyClass { private string person = ""; public string Person { set { this.Person = value; } get { return this.person; } } public static void Main() { MyClass app = new MyClass(); app.run(); } public void run() { string temp = "temp"; // Crash me this.Person = temp; } }
        Though I confess writing your own array accessor for an object is nice.
Re: Comparing Perl with C#, a simple templating example
by pg (Canon) on Oct 17, 2004 at 20:34 UTC

    Every time when I need to deal with regexp, Perl is the only choice. Not just C#, Java also had regexp support added, but Perl's is the best to this point.

    When you compare two languages, not only that usually regexp is just a small part of the language, but also it is not only about the language itself, most of the time, IDE is important for decision making, when you are looking at applications that exceeds a certain size.

    I have to give Microsoft credit for its IDE's.

    Without looking at the application you want to create, it is simply meaningless to say which language is better. It is all about the nature of the application, and which language supports its nature better. I may pick Perl for a project, but pick C# fr a different one. There is no best language, but better ones.

    At one point, some people were saying that Java woul dprevail, that didn't happen; Before java, Ada was the only candidator for future, that didn't happen either.

      When you compare two languages, not only that usually regexp is just a small part of the language, but also it is not only about the language itself, most of the time, IDE is important for decision making, when you are looking at applications that exceeds a certain size.

      Then why don't we use Java w/ Eclipse for everything? That's pretty much is the ultimate IDE situation you could have.

        jryan~

        One shouldn't use Java w/ Eclipse for everything because it doesn't fit every situation. Sometimes all you want for an ide is a read-eval-print loop. One doesn't always want the set of tools with the most features; one often wants the set of tools that fits the problem best.

        pg was merely pointing out that the tools that accompany a language are frequently as important as the language itself. After all, what is perl without CPAN?

        And on a side note, my computer is a lowly 1.4 ghz with 512 MB ram. I find eclipse to be too slow ;-)

        Boots
        ---
        Computer science is merely the post-Turing decline of formal systems theory.
        --???
Re: Comparing Perl with C#, a simple templating example
by BrowserUk (Patriarch) on Oct 17, 2004 at 12:22 UTC

    As ambrus pointed out...I'm seeing things.

    @"%(?<templ>\w)%",

    ---------------------------^

    Is there a '+' or '*' missing ^here?


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    "Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon

      The perl version of the code does not have a + or * in the regexp either, so I don't think so.

Re: Comparing Perl with C#, a simple templating example
by Vennis (Pilgrim) on Oct 18, 2004 at 08:04 UTC
    Interesting comparison.

    My conclusion is that the perl version is, when you fairly space them equally in my way (and that layout is probably personal), less then half the size/typing work of the C# version.

    Still, i think you shouldn't compare them really. Now Microsoft 'discovered' the Regular Expressions in most of their languages, you can see they really come closer to Perl. But both are just a different species (IMHO).

    Personally, I'll give C# a serious look when i need to use it for my profession. At the moment i code in Perl for conversions of data and it's perfect for the job.

    Q: Why did the Perlmonk cross the road?
    A: He wanted to escape the match.

Re: Comparing Perl with C#, a simple templating example
by dimar (Curate) on Nov 14, 2004 at 16:22 UTC
    I've abused static to simplify the example, this might be considered poor style by C# afficionados or OO purists

    That is a curious statement. Why is it considered poor style?

    some have already grumbled about MS inventing another syntax instead of following the lead of Python, PHP, or PCRE

    This is by far my biggest gripe, actually it's no longer a gripe, but rather an expected and regular annoyance. They even regularly *reinvent* their own syntax in cases where it is not necessary! It's like a game of "hide the ball" and they do it *yet again* with "Longhorn" (et al).

    The 'hide the ball' phenomenon combined with the impracticality of CSharp (sidenote and gripe: 'CSharp' and 'dotNet' are better typographical keywords than the alternatives) as a 'script oriented programming' tool render it less attractive as a general-purpose tool to use every day, like perl. The IDE is nice though.

    Nevertheless, nice writeup (was curious how EdwardG would follow up on this issue, as usual, very informative++)

      Ironically the IDE (Visual Studio) is the thing I like the least about the whole dotNet bundle. To me it feels claustrophobic, especially when compared to the freedom, focus, and simplicity of a text editor like vim. Not to mention how it also seriously chokes on large solutions (.sln).

       

Re: Comparing Perl with C#, a simple templating example
by jdporter (Paladin) on Oct 18, 2004 at 14:26 UTC
    fillTemplate() is used as a delegate (function pointer) of type MatchEvaluator
    I think you mean hashLookup, not fillTemplate.

      Thanks, fixed.

       

        C# is not as elegant as Perl but after a breaking in period where you slowly accept the shortcomings of C# it's surprising how similar they _can_ be. I submit a rather long example (yes, the Perl version is about 80% longer than it needs to be)...

        # simple html pager class use strict; use warnings; my $pager = Pager->new(); $pager->uri('foo.com/x?bar=1'); $pager->cnt(25); # from pre-query count $pager->page( $ARGV[0] || 1 ); # requested page from query arg $pager->limit(3); # recs per page print "cnt: " . $pager->cnt . "\n"; print "page: " . $pager->page . "\n"; print "limit: " . $pager->limit . "\n"; print "skip (derived): " . $pager->skip . "\n"; print "total_pages: " . $pager->total_pages . "\n"; print "html: \n" . $pager->html . "\n"; exit; ### Pager ### package Pager; use strict; use warnings;

        // simple html pager class using System; using System.Text.RegularExpressions; public class Test { public static void Main (string[] args) { Pager pager = new Pager(); pager.uri = "foo.com/x?bar=1"; pager.cnt = 25; pager.page = args[0]; pager.limit = 3; Console.WriteLine("cnt: " + pager.cnt); Console.WriteLine("page: " + pager.page); Console.WriteLine("limit: " + pager.limit); Console.WriteLine("skip (derived): " + pager.skip); Console.WriteLine("total_pages: " + pager.total_pages()); Console.WriteLine("html: \n" + pager.html()); } } public class Pager {

        Edit by castaway tidied up tags