Previous   -   Index   -   Next  >


Try Some Perl


Perl can be executed from the command line - just type perl at the command prompt, enter some lines of perl and then press cntrlD (end of file character, may be cntrlZ for other operating systems).

   bukowski -->perl
   $foo = "bar";
   print '$foo = "' . $foo . "\"\n";
      <cntrlD>
   $foo = "bar"

This sort of thing is familiar to shell users. Clearly if we want Perl to do something a little more complex then it makes sense to put the Perl code in a file. The file begins with the magic shebang line - just like we are all accustomed to doing with shell script (note that everything following a # is a Perl comment). This tells Unix which perl to use, so may vary depending on system installation (Windoze works by file extension association).
Using our favourite editor we can create a file HelloWorld.pl containing:

   #!/usr/local/bin/perl

   $foo = "Hello";
   $bar = "World";
   print "$foo $bar\n";

We have our first Perl script but before we can run it we need to make it executable.

   bukowski -->chmod 750 HelloWorld.pl
   bukowski -->HelloWorld.pl
   Hello World

Strings can be read into Perl from standard input <STDIN>. In a scalar context the string is read up to and including the newline (carriage return) character.

   $name = <STDIN>;

No prizes for guessing what the following Perl program does.

   #!/usr/local/bin/perl

   print "Please enter your name: ";
   $foo = <STDIN>;
   print "Hello $foo\n";

But did you guess what that pesky newline character would do?
You enter the name Fred and $foo ends up with the value "Fred\n". Perl provides the chomp function for removing the newline character from strings.

   chomp ($foo);

Perl allows many shorthand constructs so we could be lazy with the parentheses:

   chomp $foo;

Or write our hello.pl program as:

   #!/usr/local/bin/perl -w

   print "Please enter your name: ";
   chomp ($foo = <STDIN>);
   print "Hello $foo\n";

Note the -w flag on the shebang line. This turns on warning messages. By default Perl tries very hard not to complain or stop just because there is an error but when writing Perl code, especially for the first time, it's a good idea to turn on the warning messages.

But what about CGI?

Try this simple hello.pl program.

All those print statements are a bit long-winded for creating a form...

There has to be an easier way

But even bundling the prints into one statement does not compare favourable with ASP/PHP style coding.
We will see a lazier approach soon.


Previous   -   Index   -   Next  >

best viewed using Mozilla browsers
© k.mcmanus 2004
Valid XHTML 1.0! . Valid CSS . WCAG priority 3 approved