我试图创建一个脚本,它将从模板中生成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