0

I am trying to open and read a textfile and then write the content of this file line per line into an HTML-File. So far, I've come up with this:

use strict;     
use locale; 

my (@datei, $i);
open (FHIN,"HSS_D.txt") || die "couldn't open file $!"; 
@datei= <in>; 
close FHIN;

open (FHOUT, ">pz2.html");
print FHOUT "<HTML>\n"; 
print FHOUT "<HEAD>\n"; 
print FHOUT "<TITLE>pz 2</TITLE>\n"; 
print FHOUT '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">'; 
print FHOUT "\n</HEAD>\n"; 
print FHOUT "<BODY>\n";

for ($i = 0; $i < @datei; $i++) {
    print FHOUT "<p>$datei[$i]</p>\n"; 
}

print FHOUT "</BODY></html>\n";
close (FHOUT);

However, I get a compilation error every time and I can't figure out what's wrong. Thanks for your help!

Matt Jacob
  • 6,503
  • 2
  • 24
  • 27
  • `charset=iso-8859-1`? What is this, 1998? – melpomene Jun 02 '17 at 18:46
  • @melpomene, please do not start on charsets, it's a swamp. And I rather see it specified then blindly trusting that it would be UTF-8... which is not specified either as a pragma at the top describing the encoding used in the Perl file, neither is the encoding specified at input to output ... maybe it is Latin-1 indeed ? – vanHoesel Jun 02 '17 at 21:43

2 Answers2

1

Problem in your script

You are storing incorrect handler in your array that is your problem. @datei = <in> it should be

@datei = <FHIN>;

Some etc things you should know

1) Always put use warnings and use strict on a top of the program.

2) Don't store the whole file in an array instead you have to process the file line by line.

while (my $line = <FHIN>) 
{ 
  Do your stuff here. 

3) use three arguments for file handle. Like as follow

open my $fh,'<', "filename"

4) to access the each element from an array​ you can use Perl foreach instead of C style looping

for my $elemnts(@arrray)
{

If you have suppose want to iterate loop through its index use the following format.

for my $index(0..$#arrray)
{

Above .. means range operator$# will give the last index value

mkHun
  • 5,891
  • 8
  • 38
  • 85
1

If you had enabled warnings via use warnings or use warnings qw(all)which you should always do—you would have seen something like this:

Name "main::in" used only once: possible typo at foo.pl line 6.

That is, of course, this line:

@datei= <in>; 

The root cause of the problem is that you opened a filehandle named FHIN, but you tried to read from a filehandle named in. However, the whole operation would be better written using lexical filehandles and the three-argument form of open, which is considered a best practice:

open(my $fh, '<', 'HSS_D.txt') or die "couldn't open file $!"; 

As an aside, I've voted to close this question as off-topic because it is about a problem that was caused by a simple typographical error.

Matt Jacob
  • 6,503
  • 2
  • 24
  • 27