03/03/2003: Reading a whole file into a scalar Using Perl
Reading a whole file into a scalar Using Perl
Quite often, it is very useful to read the contents of a file into a scalar variable. The following example shows how this can be done. $fileName
is the name of the input file. $buffer
is a scalar where the file contents is stored. The $/
variable contains the end-of-record delimitor. By undefining the variable, Perl will be forced to read the entire file in one shot.
Usage:
$buffer = readFileContents($fileName)
Code:
sub readFileContents { my($fileName) = shift; my($buffer); local($/) = undef; open(FILE, $fileName) or die "couldn't open $filename for reading: $!\n"; $buffer = <FILE>; close(FILE); return($buffer); }
subscribe via RSS