Perl as a second language: Step 1

Why 2nd languages? With hello world, and readme.pl

I want to help other people kickstart new programming languages. As an experienced developer, you already what a loop is, or any other common feature: you just want to make it work. The goal of my “second language” posts is to provide that level of help.

I may explain some things that you, in particular, already know. Please be patient with these points, as others may need to know, especially if this is really just their second language. And let’s have fun with this!

Why Perl? Perl tools are found in many companies. Like me, you may be asked to extend existing programs. I am re-learning Perl now, so this is a good time to share it.

Write a program that does something

use strict;
use warnings;
print "hello world 1\n";
print("hello world, with brackets\n");

Line 1: use strict;
Line 2: use warnings;

  • Every Perl statement ends with a semi-colon. A statement can be split over more than one line to make it more readable.
  • Always start your Perl files with these two little incantations.
  • The first allows Perl to report errors caused by syntax errors and spelling errors.
  • The second enables all warnings in the block the statement is in, after the point where it occurs.
  • This means that putting strict warnings;at the top of a file enables all warnings for all the code in the file. The docs will tell you how to disable some/all warnings in some code if needed.

Line 4: print, without brackets
Line 5: print, using brackets

  • You must explicitly add a line end, “\n”, unless it is in your data, to make your text end with a newline.
  • You can call functions with or without brackets.

This is an example of Perl’s early philosophy, “There is more than one way to do it”, spelled “TIMTOWTDI”, or “TMTOWTDI”, and pronounced “Tim Toady”.

There is another philosophy, of course, a bit less radical. That philosophy is “There Is More Than One Way To Do It, But Sometimes Consistency Is Not A Bad Thing Either”, spelled only one way, TIMTOWTDIBSCINABTE, and pronounced — “Tim Toady Bicarbonate”.

The Bicarbonate guys are the guys who always use strict and use warnings. My kinda guys.

Write a self-referential program

That’s enough of the bi-carbonated philosophy issue. Let’s look at a file that reads itself. I call it readme.pl

use strict;
use warnings;

my $file_name = $0;
print "my file: $file_name\n";

# Open a file, so we can read it
open( my $fh, '<', $file_name ) or die "Can't open $file_name: $!";

my $count = 0;
while ( my $line = <$fh> ) {
    $count += 1;
    print "Me, line $count: $line";
}
close $fh;
  • Some of the lines need no further explanation, after “hello world”, above.

Line 4: my $file_name = $0;

  • All variable names start with a punctuation character. Scalars (variables that have only one thing in them) start with $, like $file_name.
  • $0 is a special variable that holds the name of the program file.
  • my is a declaration of the scope of the program. myindicates it can be accessed from this scope and its enclosed scopes. ourand localare other important options described in the docs.

Line 7(a): open( my $fh, ‘<’, $file_name )

  • Open a file and create a file handle, $fh , specifying to make it read-only ‘<’, in this case, and what file to open. On line 4 we specified that it would open its own file! Declare the filehandle to be in scope “my”, which puts it in the scope that the “open” statement is in.

Line 7(b):or die “Can’t open $file_name: $!”;

  • If the open does not work, the or specifies that the rest of the command “die, die, die!” will take effect.
  • The program will exit after the Can’t open message, because that is what die does.
  • The text in quotes will be expanded with the filename, and with an operating system error message (that’s what $! means).
  • Perl provides several short, cryptic standard variables like $!. Many of them you can ignore or replace with clearer names provided by use English, to make your program clearer.

Line 10: while ( my $line = <$fh> ) {

  • This is how a while loop is declared.
  • The opening brace, “{“, indicates the start of the “block” of code that is repeated, which is called the while loop. The end of the loop is at the matching closing brace.
  • A block is a name space in the program which inherits variables from its enclosing block and restricts my variables to the block and it’s sub-blocks.
  • The part in round brackets is the condition for the loop.the condition is always in round brackets, in all the decision/loop statements, such as “if”.
  • <$fh>, in the context of a while loop, will retrieve one line from the file at a time.

Line 15: close $fh

  • It is considered good sanitary practice, or at least a good habit, to close your file handles as soon as possible after they have been used, but if you forget, the file will be closed when Perl ends, or when the block ends where the file handle was declared.

The output looks like this:

my file: readme.pl
Me, line 1: use strict;
Me, line 2: use warnings;
Me, line 3: 
Me, line 4: my $file_name = $0;
Me, line 5: print "my file: $file_name\n";
Me, line 6: 
Me, line 7: open( my $fh, '<', $file_name ) or die "Can't open $file_name: $!";
Me, line 8: 
Me, line 9: my $count = 0;
Me, line 10: while ( my $line = <$fh> ) {
Me, line 11:     $count += 1;
Me, line 12:     print "Me, line $count: $line";
Me, line 13: }
Me, line 14: 
Me, line 15: close $fh;

End stuff

I had fun putting these little bits of code together. I hope you have fun trying them out.

If you don’t already have Perl, there’s a link for that:

Comments are good things, because feedback is your friend. And mine. If you know a clearer way to code this loop in Perl, let me know!

Originally published on Medium.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s