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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |