Skip to content

Instantly share code, notes, and snippets.

@marcusramberg
Forked from anonymous/-
Last active February 17, 2017 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcusramberg/7bae695324a38b3b2bb606fce46d5a15 to your computer and use it in GitHub Desktop.
Save marcusramberg/7bae695324a38b3b2bb606fce46d5a15 to your computer and use it in GitHub Desktop.

Manipulating the file system with Mojo::File

The Mojo framework has long had various utility functions 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 easy API for cross-platform file manipulation. It's also used across the entire Mojo framework, from Mojo::Home (now a Mojo::File subclass) to Mojo::Asset::File and +Mojo::UserAgent::Transactor.

In addition to the object constructor, Mojo::File exports some neat functions for creating new objects; path() is equivalent to new, or you can 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 quick oneliners. (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 functions).

$ 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 to learn more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment