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

 


In reply to Comparing Perl with C#, a simple templating example by EdwardG

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.