Søren Lund (slu) wrote,
Søren Lund

Hello World in Perl

The mantra There's More than One Way to Do It is well known in the Perl community. Even for something as simple as a "Hello World" program. On Rosetta Code there's three examples of "Hello World" in Perl.

I will show you only two other variantions.

The first one is a small script, that will demonstrate some aspects of Perl. Here it is:

#!/usr/bin/env perl

use strict;
use warnings;

sub say_hello {
    my $name = shift;

    die "Name must contain at least two characters" if length($name) < 2;

    print "Hello, $name\n";

say_hello $ARGV[0] || 'world';

Save it as hello.pl

The first line is the shebang line, which is a construct used in scripts on Unix (and Linux) systems. It's not strictly needed and Perl will perceive the line as a comment (because it starts with a hash (#)) and ignore it.

The next two lines are called pragmas and they restrict the use of unsafe constructs and disable enables optional warnings respectively. You should always use those in your scripts.

Then we define a subroutine, say_hello. The subroutine expects one argument: a name, which much be at least two characters long. If the provided argument is ok, then a message is printed. Note that subroutines in Perl does not have named arguments, instead all arguments are provided in the default array, @_. The shift operator pulls the first element of an array, and if no array is specified the default array is used. The die keyword will raise an exception, which usually will make the program exit with the specified warning. The subroutine and consequentially the program will only die if the length of the name is less than two, because of the statement modifier, e.g. the if-statement after the die command.

Finally we call the subroutine to say hello. The argument to the subroutine is either the first argument given on the command line or, if no such argument is given, the word 'world'.

Below is a screenshot of how it looks on a Windows 7 PC running Strawberry Perl:


That was the first example of a Hello World program. The second one is not meant to be saved as a script, instead it's called directly on the command line:

perl -E"say'Hello, world'"

The option -E means execute what follows as a script and enable all optional features. The say keyword is an optional feature, only found in newer versions of Perl. It prints its arguments to the screen followed by a new line.

Here's how it looks when run:


The second example might seem silly, but creating small one-time scripts directly on the command line can be very useful.
Tags: hello world, perl
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your IP address will be recorded