kingboa has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm new to perl and I'm trying to figure out how to open a text file and print it out to my HTML page- here are the 3 ways I have tried- I dont get an error- they just dont work
open FILE, "<test.txt"; while(<FILE>) { push @lines,$_; } foreach(reverse @lines){ print $_; } close FILE; ************************************ open(PASSWD,"test.txt") || die "Cant open: $!\n"; while(<PASSWD>) { print "hello $_"; print PASSWD; } close PASSWD; ************************************ #while ($p = <PASSWD>) # # chomp $p; # @fields= split(/:/,$p); # print "$fields[0]'s home directory is $fields[5]\n"; #} #print "$fields = $#a - $[ + 1"; close PASSWD; ************************************

Replies are listed 'Best First'.
RE: file access
by Benne (Initiate) on Feb 08, 2000 at 10:06 UTC
    You need to specify you are printing HTML content. The code look like this: open FILE, "<test.txt"; while(<FILE>) {push @lines,$_;} print "Content-type: text/html\n\n"; print "<html>" foreach(reverse @lines){ print "$_\n"; } print "<html>" close FILE;
Re: file access
by dlc (Acolyte) on Feb 08, 2000 at 18:36 UTC

    your first fragment should work. try passing a "|| die $!" at the end of the open call, to make sure you have read permissions on it if it keeps failing. try something like this much cleaner):

    die $! unless open F,"test.txt";
    print reverse <F>;
    close F;
     

    printing <PASSWD> in the second example won't work--in this syntax you are printing $_ to the filehandle PASSWD (which you opened read only). if you are running with warnings turned on ($^W != 0 or perl -w) you will get a runtime warning (compile time warning in 5.6). You are using strict and -w right?

    the bigger questions, of course, are why are you printing the contents of the password file to an HTML page? and are you print the content type as required for cgi scripts?

    darren

RE: file access
by Fistagon (Initiate) on Feb 08, 2000 at 23:20 UTC
    Try this:
    #!/usr/bin/perl open(readfile, "yourfile.html"); @lines=<readfile>; close(readfile); print "Content-type: text/html\n\n"; print @lines;
Re: file access
by Anonymous Monk on Feb 09, 2000 at 20:40 UTC
    this will open a file, and send the content of the file to the browser print "Content-type: text/html\n\n"; open (file,"path/file.txt") || print "Could not open\n"; while (<file>) { print $_; } close(file); } mark
Re: file access
by stephen (Priest) on Feb 09, 2000 at 05:05 UTC
    I'm not quite sure why you're using the 'reverse' word above, unless you want to print the lines of the file in reverse order.

    Here's yet another way of doing the same thing:

    #!/usr/bin/perl use strict; use File::Copy; print STDOUT "Content-type: text/plain\n\n"; copy('yourfile.txt', \*STDOUT);

    (Untested as always...)