I'm basing the majority on my Perl scripts on the following template/skeleton:
#!/usr/bin/perl -w
use strict;
use utf8;
$| = 1;
binmode(STDOUT, ":utf8");
# my code goes here.
The things achieved by this template:
-w
)use strict
)use utf8
+ binmode(STDOUT, ":utf8")
)$| = 1
)My question is:
How can my template be improved to better reflect Perl best-practices?
Replace the -w
with use warnings
. It allows you to disable warnings lexically should you need to. See perllexwarn.
The use utf8
pragma is for when your source code is in UTF-8. If it is, great. If not... I don't recommend adding things that you don't actually use. Similarly, don't set STDOUT to UTF-8 unless you're actually producing it.
Disabling buffering will reduce performance. Don't do it unless you need to, and then limit the scope to the block where it's necessary.
I like to include a statement to explicitly state the minimum version of Perl required to run the script. This makes the error messages more meaningful if it doesn't compile due to someone using an older version of Perl. e.g.
BEGIN { require 5.00801 }
I use that particular incantation instead of something like use v5.8.1
because it's backwards-compatible with the versions of Perl I'm trying to "support" with a meaningful error message.
Here's mine, although I must admit that sometimes I just start typing without using the template. I set it up as a modulino so it's easy to add testing to it later:
#!perl
package App::XXX;
use utf8;
use 5.010;
use strict;
use warnings;
use vars qw($VERSION);
$VERSION = '0.01_01';
__PACKAGE__->run( @ARGV ) unless caller;
sub run
{
my( $class, @args ) = @_;
}
1;
If you want to set all of your filehandles to some encoding automatically, you could add the open
pragma:
use open IO => ':utf8';
I have another template for documentation that I add later.
Also, some people have editor sequences that they add as comments at the top or the bottom of the script. Perhaps:
# -*- Mode: cperl; coding: utf-8; cperl-indent-level: 4 -*-
# vim: ts=4 sts=4 sw=4:
Since I put my scripts into distributions, the installation process automatically fixes up the shebang line so it doesn't matter what I put there.
How about throwing in some documentation?
=head1 NAME
name here
=head2 SYNOPSIS
short synopsis here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With