Home > Articles > Web Development > Perl

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

Main Sample

In this section, we combine the knowledge that we provided throughout this chapter. We present the full example program, which you should easily understand. We use the Console class, since we want you to feel comfortable when combining .NET types with Core Perl statements and expressions.

Our sample performs calculations of binary operations (+, , *, /). It gets as an input an expression (x op y) where x and y are integer positive numbers and op is one of the four operators mentioned above. Our .NET program validates the input using Perl regular expressions (!) and then evaluates the expression. To test the following code, refer to the MainSample\BinOper folder.

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

# Full qualified type reference
q(System.Console)->WriteLine("Please enter expression to 
                             evaluate:");

# Get an expression from the user – Another way to refer to 
# Console class
my $expr = System::Console->ReadLine();

#remove whitespaces from $expr
$expr =~ s/\s*//g;

# Check for valid format
if ($expr =~ /(^\d+)([\+,\-,\*,\/]{1})(\d+$)/)
{
   # Evaluate user expression
   my $result = eval $expr;
    
   # Check if the result is OK
   if (!defined $result) 
   { 
      die "Illegal operation: $expr"; 
   }

   # Output – Refer to Console without namespace
   # specification
   Console->WriteLine("Result: {0}\n", $result);
}

# Handle wrong input
else
{
   die "Incorrect expression format";
}

As you can see, we take advantage of the powerful Perl constructions to validate input. eval simply evaluates an expression if it was supplied in correct form. The die statement is used to handle errors. Examples of running the program may look like this:

Please enter expression to evaluate:
64 + 36
Result: 100
------------
Please enter expression to evaluate:
d-5
Incorrect expression format at binoper.pl line 38.
------------
Please enter expression to evaluate:
10 / 0
Illegal operation: 10/0 at binoper.pl line 27.

Take some time to play with the program. Supply different inputs and examine the response. Enjoy!

  • + Share This
  • 🔖 Save To Your Account