[英]How do I write to a file with a Perl Catalyst app?
在Root.pm内部,我有一个子索引函数,例如:
sub index :Path :Args(0) {
my ( $self, $c ) = @_;
#basic file IO attempt to write to a file
my $file = 'test3.log';
open(my $fh, '>>', $file);
print $fh "I can write to a file\n";
close $fh;
$c->stash({
template => 'index.tt',
});
#debug that doesnt work for some reason
$c->log->debug('Does this actually work?');
}
如何写入与调用它的pm相同或不同目录中的文件?
您始终可以使用MyApp->path
找到应用程序的根目录,但是在运行时生成文件时,您可能希望避免将这些内容放入应用程序区域,因为您的权限在生产中可能与开发中有所不同。
我见过很多人所做的就是将这些东西放在/var
。
您可能确实将文件写入了“当前”目录。 但是此目录不在您的Root.pm
所在的位置。 如果您使用scripts
目录中的webserver脚本启动Catalyst, test3.log
在其中启动脚本的地方找到test3.log
。
要查找当前文件所在的目录,请使用__FILE__
并扩展路径名:
use File::Basename;
# ...
sub index :Path :Args(0) {
my ( $self, $c ) = @_;
#basic file IO attempt to write to a file
my $dirname = dirname(__FILE__);
my $file = $dirname.'/test3.log';
open(my $fh, '>>', $file) or die $!;
print $fh "I can write to a file\n";
close $fh;
# ...
}
有关dirname
例程的更多信息,请参见https://metacpan.org/pod/File::Basename 。
您应该使用Log :: Log4perl :: Catalyst之类的软件包,而不是在每种方法中都写入磁盘,以防止同时写入同一文件。 它也更加灵活,例如使用不同级别的日志(调试,警告,错误),不同输出等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.