On Fri, Jun 08, 2001 at 09:46:18AM -0700, Matt Lyon wrote:
> I was wondering...
> if there are any one-page perl-script-templates that're pre-done
> that handle typical perl issues, where the header has all the use-strict /
> debugging stuff in it... that you can edit and morph into your own scripts.
>
> I had one for bash that was awesome named new_script... it really helped out
> with things like debugging and handling command-line arguments. plus, it's
> output looked really nice.
>
I've included one that I sometimes use below. It's only useful for a
certain class of scripts, but I've found it handy enough. You'll
probably also find that you end up keeping a library of snippets and
functions for particular purposes, like networking, CGI, whatever. As
time goes by, you'll start mving them into packages and reusing them
from there. But anyway, this one has pretty much all the stuff I want a
serious script to contain (-w and strict, command-line options,
debugging framework, config file parsing).
You could do more, like adding signal handlers, tidying things up by
using File::Basename, and so on.
cheers
rob c
#!/usr/bin/perl -w
use strict; #make me behave.
use vars qw($opt_usage $opt_config $opt_verbose $opt_debug);
use vars qw($conf_item $conf_value %config);
use Getopt::Long; #for command line options
#retrieve options
GetOptions('h|help' => \$opt_usage,
'c|config=s' => \$opt_config,
'v|verbose' => \$opt_verbose,
'd|debug' => \$opt_debug);
#Usage message takes precedence over all other command-line parameters.
$opt_usage && &showUsage;
$opt_debug && print STDERR "Debug mode is ON ...\n";
open CONFIG, $opt_config or die "Couldn't open config file $opt_config:
$!\n";
while (<CONFIG>) {
chomp;
s/\s+#.*//; #strip trailing spaces
next if /^#/; #skip comments
next if /^\s*$/; #skip blank lines
if (($conf_item, $conf_value) = /(.*?)\s*=\s*(.*)/) {
$config{$conf_item} = $conf_value;
$opt_debug && print STDERR "CONFIG: $_\n";
} else {
warn "bad config line: $_\n";
#assume "item = value" in conf file
}
}
################################################################################
## START MAIN
## END MAIN
################################################################################
## If -h or --help, show usage and exit
sub showUsage {
my $msg = <<EOF;
$0: <Program Description>
SYNOPSIS
$0 [options] file(s)
USAGE
OPTIONS
-d, --debug Show debugging info on STDERR
-v, --verbose Be verbose (on STDOUT)
-c, --config Select config file to be used by $0
-h, --help Show this message and exit
EXAMPLES
EOF
die $msg;
}