-
-
Save anonymous/46e367e8c84332fa65dfc3c7ea585e6a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Manipulating the file system with Mojo::File | |
The Mojo framework has long had various utils for file manipulation, but | |
recently in version 7.15 they were collected in a new class, Mojo::File. | |
This class gives a very convenient and simple API for cross-platform file | |
manipulation. It's also used consistenly across the entire Mojo framework, | |
from Mojo::Home (now a Mojo::File subclass) to Mojo::Asset::File and | |
Mojo::ByteStream. | |
In addition to the regular ->new constructor, Mojo::File exports some neat | |
functions for creating new objects; path is equivalent to new, and you can | |
also use tempdir and tempfile to get a object representing a temporary file | |
or directory. | |
``` | |
use Mojo::File qw/path tempfile/; | |
my $passwords=path('/etc/passwd')->slurp; | |
my $tmpfile=tempfile->spurt('OMG Look at her file')->move_to('/home/her/file'); | |
``` | |
Mojo::File is also supported by the ojo module, for simple oneliner usage. | |
(If you don't know ojo, it's a conveniently named class to allow perl to | |
take the -Mojo flag, and expose a bunch of single letter commands). | |
``` $ perl -Mojo -E 'say r j f("hello.json")->slurp'``` | |
Mojo::File also has some useful methods for iterating over a directory or | |
even a full tree of files. The list method lets you get all the files, | |
and optionally directories and hidden files in a given directory, and | |
manipulate the results with all the power of Mojo::Collection, while | |
list_tree does the same recursively. | |
``` $ perl -Mojo -E'say for f('/tmp')->list_tree->map(sub { uc })->each' | |
Finally, Mojo::File supports some simple overloading. Just interpolate it | |
in a string, and it will do the right thing. Or let's say you want to | |
iterate over each path part of the current directory: | |
``` perl -Mojo -E'say $_ for f->@*' ``` | |
So easy! I think you will have fun with this module. Check out [the | |
documentation](http://mojolicious.org/perldoc/Mojo/File) to learn more. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment