stringperlslurp

In Perl, how can I read an entire file into a string?


I'm trying to open an .html file as one big long string. This is what I've got:

open(FILE, 'index.html') or die "Can't read file 'filename' [$!]\n";  
$document = <FILE>; 
close (FILE);  
print $document;

which results in:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN

However, I want the result to look like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

This way I can search the entire document more easily.


Solution

  • Add:

     local $/;
    

    before reading from the file handle. See How can I read in an entire file all at once?, or

    $ perldoc -q "entire file"

    See Variables related to filehandles in perldoc perlvar and perldoc -f local.

    Incidentally, if you can put your script on the server, you can have all the modules you want. See How do I keep my own module/library directory?.

    In addition, Path::Class::File allows you to slurp and spew.

    Path::Tiny gives even more convenience methods such as slurp, slurp_raw, slurp_utf8 as well as their spew counterparts.