简体   繁体   中英

How do I write to a file with a Perl Catalyst app?

Inside of my Root.pm I have a sub index function as such:

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?');    
}

How can you write to a file that is in the same or different directory as the pm that calls it?

You can always find the root of your application with MyApp->path but when you are generating files at runtime you might want to avoid putting that stuff in the application area since you're permissions to that might be different in production from development.

What I've seen a lot of people do is put that stuff under /var .

You propably did write a file to the "current" directory. But this directory is not where your Root.pm is located. In case you start up your Catalyst with the the webserver script in the scripts directory, you will find test3.log where you started the script from.

To find out the directory, where your current File is located, use __FILE__ and extrect the path name:

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;

    # ...
}

See https://metacpan.org/pod/File::Basename for further information about the dirname routine.

You should use package like Log::Log4perl::Catalyst instead of writing to disk in each method to prevent concurrent writing to the same file. It's also much more flexible, like using different level of log (debug, warn, error), different outputs, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM