2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018

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