I saw this in a piece of code that I was reviewing today:
# first arguement is a -f; collect it and ignore it for now
my $optionalArgument = shift;
# get filename of the config file
my $configFile = shift;
In reply, I added this comment:
Eventually this should use one of the Getopt modules (like Getopt::Long - parsing the cmd line manually can lead to bugs, especially as code is refactored.
The response that I got back was essentially, "we use this method in a lot of our code - how can it lead to bugs?"
I rattled off a few of the advantages that sprang to mind:
- named params tend to be more flexible (it is easy to add params at a later date without risking breaking anything)
- named params are less error-prone because they are not order-dependent (e.g., shift)
- named params make it easier from the caller's perspective because they don't have to remember the exact order of the arguments
- meaningful param names aid memory and add clarity
- Getopt::Long provides basic parameter validation (required/optional/string/integer/etc)
- Getopt::Long makes it trivial to use flags and named params simultaneously
After looking back at the list, I realized that I was arguing
for using named parameters and
Getopt::Long - not explaining why parsing the command line manually is a Bad Idea.
I admit that my initial comment was more of a conditioned knee-jerk response than a well thought out reply. To be honest, I haven't really thought about it. I always use Getopt::Long when I need to parse the command line, but apparently I'm using it to gain several advantages, not to avoid disadvantages. Was I incorrect when I said "parsing the cmd line manually can lead to bugs"?
How do you parse the command line, and why? What are the risks for not using a module?
Thanks in advance for the input. pun intended ;-)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.