Debugging Perl on Linux – Just __END__ it now! it later.

The art of debugging differs, some, with each language and it’s specific tools. Perl provides an interesting challenge to programmers since it, like most linux-originating languages, has no real IDE wherein it can be debugged step by step with breakpoints and like methodologies. Instead, the perl programmer must resort to using print statements, logging mechanisms, and then there is the __END__.

The __END__ directive does just what you would think it would do: stops execution of the perl script. This can be handy in a few ways, but first let’s see it in action:

#!/usr/bin/perl -w

print "This is line one!n";
print "This is line two!n";
print "This is like three but is never executedn";
this doesn't even have to be code cause
it never gets interpreted as code.

Run that and you will get:

% ./
This is line one!
This is line two!

As you can see, the __END__ directive must be alone on its own line, with nothing before it. It’s picky that way. Don’t upset the __END__ or it won’t do it’s job.

The most obvious usage for the __END__ is cutting execution short so as to debug the top portions of the script before adding in the lower half. It doesn’t matter, either, if there are syntax errors in the lower portion since it won’t be parsed as code. How cool is that!?

The second use for __END__ is to include data within the code file. Though not generally a best practice, it has it’s uses in times and in seasons. You access the data under the __END__ directive through the file handler, like so:

#!/usr/bin/perl -w
$words = 0;
$chars = 0;
$words += split;
$chars += length;
print "Characters : $charsn";
print "Words : $wordsn";
print "Lines : $.n";
This is a bit of text designed to show
the concept of data underneath
the code in Perl using the __END__
directive and the DATA file handler.

And when you run this you get:

% ./
Characters : 142
Words : 27
Lines : 4

So there you have it! Now you too can use the __END__ to justify your means!

Leave a Reply