我試圖創建一個腳本,它將從模板中生成perl代碼,並且我無法理解所引發的錯誤以及爲什麼我的解決方法修復了它。如何打印在here-doc中嵌入的代碼爲詞法文件句柄
這個例子是人爲的,但它說明了這個問題:
use strict;
use warnings;
my $name = shift; # from @ARGV
my $file = sprintf "%s.pm", $name;
open my $fh, ">", $file
or die "error: open(>, '$file'): $!";
print $fh << "MODULE";
package $name;
#
# blah blah
#
use strict;
use warnings;
require Exporter;
our \@ISA = qw| Exporter |;
our \@EXPORT = qw| |; # automatic exports
our \@EXPORT_OK = qw| |; # on-demand exports
# CODE
1;
MODULE
close $fh;
當運行此腳本時,我收到以下錯誤:
$ perl script.pl Foo
Invalid version format (non-numeric data) at script.pl line 11, near "package "
syntax error at script.pl line 11, near "package $name"
BEGIN not safe after errors--compilation aborted at script.pl line 17.
本來這個腳本只是打印到stdout,而不是寫入文件 - 沒有錯誤拋出。在添加文件處理和接收這個錯誤之後,我然後試圖使用一個裸文件句柄 - 再次沒有錯誤拋出。
所以,如果我只是將「$ fh」替換爲「FH」,那麼腳本將按預期工作。關於詞法文件句柄導致它窒息的是什麼?
嘗試使用IO :: Handle和$ fh-> print()語法。 – AKHolland
另一個解決方法...'print {$ fh} <<「MODULE」;''參考'perldoc -f print' – toolic
@AKHolland:方便地,'IO :: File'(以及IO :: Handle')根據需要由任何Perl v5.14或更高版本加載。這意味着你可以使用任何文件句柄,就好像它是一個'IO :: File'對象,而不事先添加顯式的'use IO :: File'。 – Borodin