Home > Articles > Web Development > Perl

  • Print
  • + Share This
This chapter is from the book

Main Function

Let's look at a simple program written in C# that performs the same action as our first sample: It displays the single line "Hello from C#." (If you don't know C#, you can refer to Appendix B, "C# Survival Guide for PerlNET Programmers.") We saved the program in the HelloCs folder.

// Hello.cs
using System;

class Hello
{
   public static void Main(string[] args)
   {
      Console.WriteLine("Hello from C#");
   }
}

As you can see, we defined a class with a single static method Main, and this is the minimum requirement of each .NET program.

Unlike C# or other .NET-compliant languages, in PerlNET you are not required explicitly to define the Main function and wrap your program by the class, which means that our PerlNET programs may be written just as a sequence of statements (like script) and saved in a .pl file. In Chapter 12, we will see that, after compiling, our programs are implicitly wrapped by the class that has the static Main method. This method is an entry point to our program, and it encapsulates all the statements that we wrote in the .pl file in the script-like manner. However, you may want to define the Main method explicitly. We will see that it is useful when we learn how to create a graphical user interface in Chapter 14.

Here is how we may rewrite our first sample with the Main function definition. 

#
# HelloMain.pl
#
use namespace "System";
use PerlNET qw(AUTOCALL);

=for interface
   public static void Main(str[] args);
=cut

sub Main
{
   Console->WriteLine("Hello from Main function");
}

The code for the program resides in HelloMain. This program introduces additional syntactic structures that are not present in Core Perl. The first thing you may notice is the following POD =for interface block:

=for interface
   public static void Main(str[] args);
=cut

We will make wide use of these blocks when learning about creating .NET components later in the book. Perl is a dynamic type language and recognizes neither method modifiers (public, static) nor types. As we want to preserve Perl features and still tap into the .NET environment, we are required to find a compromise that is acceptable to both sides. The solution is to use a special =for interface block, where all .NET-specific definitions go on. As you can see, our sample defines the Main method with the same modifiers, return type, and signature as the C# program.

  • + Share This
  • 🔖 Save To Your Account