The T-Files


Tue, 18 Jan 2005

The thousand and one reasons to love Perl: [12] __DATA__

Sometimes your Perl script is just that: a small script for a specific task that is contained in a single file. Because a single file is easier to deploy and track than applications that span many files (program, configuration and so on) you want to keep it small. However, at the same time, you want to have the script read something from a data file, for example a template for the report it produces, or a list of people to email the report to. Using Perl's many quoting functions (especially for multi-line strings) you could just throw that data into a variable. But sometimes a file handle is more convenient, if only because you can easily loop over it line by line. No problem, you can just include that data in the same file right after the script and the special __DATA__ keyword. You can read from this __DATA__ section just like you would read from a file:

printf '%03d> %s', $., $_ while (<DATA>)  # special filehandle DATA
__DATA__
Once upon a midnight dreary, while I pondered weak and weary,
 Over many a quaint and curious volume of forgotten lore,
 While I nodded, nearly napping, suddenly there came a tapping,
 As of some one gently rapping, rapping at my chamber door.
 `'Tis some visitor,' I muttered, `tapping at my chamber door -
 Only this, and nothing more.'