C# & Perl
by Talbott Crowell


Listing One
(a)
# Perl
@fruit = ("apples", "pears", "bananas", "oranges");
# turn the array into one scalar string
$line = join("\t", @fruit);
print $line, "\n";


(b)
// C#
string[] fruit = {"apples", "pears", "bananas", "oranges"};
// turn the array into a single string
      string line = String.Join("\t", fruit);
      Console.WriteLine(line);

Listing Two
(a)
# Perl
$beverages = "iced tea\troot beer\tcoffee\twater";
# turn a string into an array
@drinks = split("\t", $beverages);
foreach $drink (@drinks) {
   print $drink, "\n";
}

(b)
// C#
string beverages = "orange juice\troot beer\tcoffee\twater";
char[] separator = {'\t'};
// turn a string into an array
string[] drinks = beverages.Split(separator);
foreach (string drink in drinks) {
   Console.WriteLine(drink);
}

Listing Three
(a)
// C#
string greeting = "hello";
// the following is not allowed: Join is not an instance method
greeting.Join("\t", fruit); // error

// must use the String class name to invoke the static Join method
String.Join("\t", fruit);  // OK

(b)
// C#
string beverages = "orange juice\troot beer\tcoffee\twater";

// the following is not allowed: Split is not a static method
String.Split(separator, beverages); // error

// must use a String object reference to invoke the Split method
beverages.Split(separator);         // OK

Listing Four
(a)
# Perl
@drinks = ("orange juice", "root beer", "coffee", "water");
foreach $drink (@drinks) {
   print $drink, "\n";
}

(b)
// C#
string[] drinks = {"orange juice", "root beer", "coffee", "water"};
foreach (string drink in drinks) {
   Console.WriteLine(drink);
}

Listing Five 
(a)
# Perl
@drinks = ("orange juice", "root beer", "coffee", "water");
foreach $drink (@drinks) {
   print $drink, "\n" if $drink =~ /ee/;
}

(b)
// C#
string[] drinks = {"orange juice", "root beer", "coffee", "water"};     
Regex regex = new Regex("ee");
foreach (string drink in drinks) {
   if (regex.IsMatch(drink)) {
      Console.WriteLine(drink);
   }
}

(c)
# Perl
@drinks = ("orange juice", "root beer", "coffee", "water");
foreach (@drinks) {
   print if /ee/;
}

Listing Six
// C#
string[] drinks = {"orange juice", "root beer", "coffee", "water"};     
foreach (string drink in drinks) {
   if (Regex.IsMatch(drink, "ee")) {
      Console.WriteLine(drink);
   }
}





1

