如何使用Perl Catalyst应用程序写入文件?

时间:2014-03-19 11:40:46

标签: perl catalyst

在我的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相同或不同目录的文件?

3 个答案:

答案 0 :(得分:1)

您始终可以使用MyApp->path找到应用程序的根目录,但是当您在运行时生成文件时,您可能希望避免将这些内容放在应用程序区域中,因为您在生产中的权限可能会有所不同来自发展。

我见过的很多人都把这些东西放在/var下。

答案 1 :(得分:0)

您可以将文件写入“当前”目录。但是此目录不是Root.pm所在的目录。如果您使用scripts目录中的webserver脚本启动Catalyst,您将找到启动脚本的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

答案 2 :(得分:0)

您应该使用Log::Log4perl::Catalyst这样的包,而不是在每种方法中写入磁盘,以防止并发写入同一文件。它也更灵活,比如使用不同级别的日志(调试,警告,错误),不同的输出等。

相关问题