Skip to content

Instantly share code, notes, and snippets.

/-

Created February 17, 2017 08:32

Revisions

  1. @invalid-email-address Anonymous created this gist Feb 17, 2017.
    44 changes: 44 additions & 0 deletions -
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    # 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.