laziness, impatience, and hubris | |
PerlMonks |
Using the DATA file handle for ARGVby samwyse (Scribe) |
on May 30, 2013 at 14:30 UTC ( [id://1036065]=perlmeditation: print w/replies, xml ) | Need Help?? |
The TrickFrequently I find myself with a one-off data file that I need to analyze with a one-off script. It's nice to keep the script with the data, so I generally put the script in the data file, with a __DATA__ marker separating the two parts. At this point, I have another problem. One-off scripts benefit tremendously by the use of Perl's command line flags that write code for you, the '-p' and '-n' flag in particular. Those two flags wrap your code in a while (<>) ... loop, which unfortunately reads all the files listed on the command line, or STDIN if there aren't any. My data, needless to say, is in the DATA file handle. I mentioned this in the chatterbox, and choroba had the answer: BEGIN { *ARGV = *DATA unless @ARGV }I especially like the unless clause, since it lets me override the data source. I can see using this for test cases, where I have a bunch of default test data but can easily test against other data files as well. Why It WorksWe're overwriting one typeglob (*ARGV) with another (*DATA). A typeglob contains Perl's internal representation of everything known about the given name, which includes any scalars, arrays, hashs, or filehandles. In this case, the ARGV set of variables have several "magical" properties, which are listed in perlvar:
The assignment *ARGV = *DATA will replace all of these with the only-slightly-less magical DATA values, which is cleverly not mentioned in perlvar, only in perldata. In this case, only the filehandle has any special properties. This means that the assignment also overwrites the $ARGV and @ARGV values with the undefined values of $DATA and @DATA, but I can't see many cases where you'd need those values once ARGV is gone. If I'm wrong, however, ambrus has pointed out that you could change the IO slot only, by *ARGV = *DATA{IO} See Also...'perl -e' and '__DATA__' What's wrong? Re: $. - smarter than you might think Many Thanks to...First and foremost, choroba presented the idea in chatterbox. shmem prodded me to write the "Why It Works" section, and also provided two of the "See also" links. ambrus reminded us how to overwrite just one slot in a typeglob.
Back to
Meditations
|
|