2017-04-10 47 views
3

我試圖找出如何使用Perl中的定界符來創建一個簡單的HTML文件,但我不斷收到創建HTML文件失敗,裸字錯誤

Bareword found where operator expected at pscratch.pl line 12, near "<title>Test" 
    (Missing operator before Test?) 
Having no space between pattern and following word is deprecated at pscratch.pl line 13. 
syntax error at pscratch.pl line 11, near "head>" 
Execution of pscratch.pl aborted due to compilation errors. 

我想不出問題是什麼。這是全部的腳本:

use strict; 
use warnings; 

my $fh; 
my $file = "/home/msadmin1/bin/testing/html.test"; 

open($fh, '>', $file) or die "Cannot open $file: \n $!"; 

print $fh << "EOF"; 
<html> 
    <head> 
    <title>Test</title> 
    </head> 

    <body> 
    <h1>This is a test</h1> 
    </body> 
</html> 
EOF 

close($fh); 

我周圍使用EOF單引號和雙引號嘗試。我也嘗試轉義所有<>標籤,但沒有幫助。

我該怎麼做才能防止這個錯誤?

編輯

我知道有模塊,在那裏,將簡化這一點,但我想知道是什麼問題,與此之前,我簡化了模塊的任務。

EDIT 2

的錯誤似乎表明,Perl是看定界符內的文本作爲替代由於在結束標記的/。如果我將它們轉義出來,那麼錯誤的一部分就會消失,但是其餘的錯誤依然存在。

+6

刪除空間後''<<。 – melpomene

+0

謝謝!請做出答案,以便我可以選擇它。 – theillien

+1

有了這個空間,它是一個移位操作http://perldoc.perl.org/perlop.html#Shift-Operators,所以Perl將HTML解釋爲Perl代碼 – ysth

回答

1

刪除<< "EOF";的盈利空間,因爲它與文件句柄打印沒有很好的互動。

這裏有不同的工作/非工作的變體:

#!/usr/bin/env perl 

use warnings; 
use strict; 

my $foo = << "EOF"; 
OK: with space into a variable 
EOF 

print $foo; 

print <<"EOF"; 
OK: without space into a regular print 
EOF 

print << "EOF"; 
OK: with space into a regular print 
EOF 

open my $fh, ">foo" or die "Unable to open foo : $!"; 
print $fh <<"EOF"; 
OK: without space into a filehandle print 
EOF 

# Show file output 
close $fh; 
print `cat foo`; 

# This croaks 
eval ' 
print $fh << "EOF"; 
with space into a filehandle print 
EOF 
'; 
if ([email protected]) { 
    print "FAIL: with space into a filehandle print\n" 
} 

# Throws a bitshift warning: 
print "FAIL: space and filehandle means bitshift!\n"; 
print $fh << "EOF"; 
print "\n"; 

輸出

OK: with space into a variable 
OK: without space into a regular print 
OK: with space into a regular print 
OK: without space into a filehandle print 
FAIL: with space into a filehandle print 
FAIL: space and filehandle means bitshift! 
Argument "EOF" isn't numeric in left bitshift (<<) at foo.pl line 42. 
152549948