Input Delimiter
Normally, reading from a file is done one line at a time. But sometimes that is not very convenient. What if you want to read in text one paragraph at a time? Or maybe your data is separated by TAB characters rather than newline characters?
Perl offers a special variable $/ which lets you control how input is read. Normally the value of $/ is "\n" which means to read one line at a time. But you can change it! Set it to "\t" to read one tab character at a time. You can even set it to multiple characters, like "\n\n" to stop only when there is a blank line (paragraphs).
But what if there is an extra blank line between paragraphs? This is a need that is likely enough that the makers of Perl added a special case to cover it: $/ = "" for paragraph mode. Any number of blank lines can separate a paragraph.
Note: This is a global variable, and affects all filehandles that you might open. To minimize its impact, localize it. Inside the block or subroutine where the file is being read from, add a line like this:
local($/) = "";
This way, once that block or subroutine exits, the previous value of $/ will be restored, and your change won’t affect other parts of the program that read from files.
But what if you’re processing using a command-line program, using the -n and -e options? Well, use the -0 option (thats a zero, not a capital Oh). Follow the 0 with one or more digits to specify an octal (base 8) representation of the character you want assigned to $/. Or use -00 for paragraph mode (like $/=""). To slurp the entire file use -0777 (777 is not a valid character in octal, so it will never be found in the file).

Thanks for this tip! It saved my life on a project that I am doing at work!
Comment by Blake H — July 22, 2008 @ 5:23 am
Glad to help. See also the File::Slurp module.
Comment by William Ward — July 22, 2008 @ 7:40 am
[...] In an earlier entry (was it really six years ago?) I talked about the usage of $/ and the -0 command-line option to Perl to change the input delimiter. But there’s another way to read in “slurp” mode that isn’t described there, the File::Slurp Perl module. [...]
Pingback by Perl Tips Blog from Bay View Training » A Better Way to Slurp — July 22, 2008 @ 7:52 am