Perl is an awesome language. I like it very much more than Python because you can put some imagination inside your code, doing things with your style. I like very much the loose typing because you don’t have to care about the content in your variables: numbers, strings, objects are almost the same. You have to care about what you are doing, not how.
Commenting your code is very important for you and for everybody else that will see it. And if you are writing a standalone script it’s very useful to give hints about the usage without reading the code. Perl has a integrated comment system called Pod that can be used to generated documentation files in a number of format, but how can you display something on the command line by using the common –help parameter?
The answer is the Pod::Usage package. It’s a very powerful package, but I will use it in a minimal way. The official documentation will tell you everything you need to know, but let’s take a taste.
#!/usr/bin/perl =head1 Example script This is an example script to taste the Pod::Usage package. =head1 SYNOPSIS example.pl [--help] --source=18.104.22.168 --target=22.214.171.124 Options: --help Displays this help --source A source --target A target =cut use strict; use Getopt::Long; use Pod::Usage; my ($help, $source, $target); GetOptions( 'source=s' => $source, 'target=s' => $target, 'help' => $help ); pod2usage(1) if $help; [...]
So how does this work? I use the Getopt::Long package to manage command line parameters. I pass two string parameters (source, target) and a flag (help). If flag is set I call the pod2usage function from Pod::Usage with a ‘1’ as parameter. The function will print out everything contained inside the SYNOPSYS paragraph and will exit the script with code 1 (or whatever number you passed). That’s all!