First Perl Program

Code

Let's call it first.pl

 1~$ nl -ba first.pl
 2     1	#!/usr/bin/env perl
 3     2	
 4     3	use strict;                        # important pragma
 5     4	use warnings;                      # important pragma
 6     5	
 7     6	print "What is your username? ";   # print out the question
 8     7	my $username = <STDIN>;            # ask for username
 9     8	chomp($username);                  # remove “new line”
10     9	print "Hello, $username.\n";       # print out the greeting

Check syntax

Make it a habit when coding in Perl.

1perl -c first.pl

Make executable

1chmod u+x first.pl

Sample Run

1~$./first.pl 
2What is your username? mikeymouse
3Hello, mikeymouse.

"mikeymouse" was the keyboard input and taken using <STDIN> in line 7. If you comment out line 8, then your output would become:

1Hello, mikeymouse
2.

for obvious reasons.

Best Practice

As for line 3 and 4, it is best used always.

  • use strict - tells the perl compiler to use the strictest possible rule
  • use pragma - to warn you (the programmer) if there are questionable code
  • check syntax - of course, the check syntax shown earlier