P is for Practical | |
PerlMonks |
Re: Parsing @ARGV w/ Map Functionby ELISHEVA (Prior) |
on Feb 14, 2011 at 07:18 UTC ( [id://887932]=note: print w/replies, xml ) | Need Help?? |
I'm just wondering if there's enough flexibility to do all this.... map's a great tool and I also wanted to see just how far I could go with it when I first learned it. Map does indeed have the flexibility you seek. That {...} block can contain nearly anything, including long if...elsif...else statements. Thus anything you can do with a sequence of map statements most likely can be done in one. The main limitation on map is this: you can't "return" from within the {...} block. If you try, you will return from the surrounding subroutine and not just quit mapping or skip an array element. What you can do if you want to skip an array element (e.g. a bad command option) is return an empty list: (). You can also do that if you want to put the data for that particular array element into some other data structure than the hash you are building. Your original spec would look something like this. Note the use of if..elsif to vary the result of the map based on a regular expression match. This works because map only cares about the last executed line, not the last line visually appearing in the block:
You could also stuff the filenames into an array so that you wouldn't have to reconstruct the array order by scanning the hash. This example also illustrates the technique of returning () when you want to do something with an array element other than place it immediately in the hash:
The main thing to worry about with map is going a little bit crazy and trying to do everything in a map (I know I did at first). Usually, if the map block gets to be more than a few lines I'll define a subroutine and call that subroutine within map, like this:
On a final note, learning exercises aside, for real option processing, do take a look at the core module Getopt::Long. It can also convert @ARGV into a hash and goes well beyond the list of argument processing features you discussed above: collapse multiple options into arrays, auto define options (e.g. --noredirect as well as just --redirect), and much, much more.
In Section
Seekers of Perl Wisdom
|
|