The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Module::Generic::File - File Object Abstraction Class

SYNOPSIS

    use Module::Generic::File qw( cwd file rootdir tempfile tempdir sys_tmpdir stdin stderr stdout );
    my $f = Module::Generic::File->new( '/some/file' );
    $f->append( "some data" );
    $f->open && $f->write( "some data" );
    my $d = file( "/my/directory/somewhere" );
    $d->makepath;
    $d->chdir;
    $d->contains( $f );
    my $d = file( $tmpdir )->mkpath->first;
    $f->is_part_of( $d );
    $f->touchpath;
    my $f = $d->child( "file.txt" )->touch;
    $f->code == 201 && say "Created!";
    say "File is empty" if( $f->is_empty );
    
    my $file = tempfile();
    my $dir  = tempdir();
    
    my $tmpname = $f->tmpname( suffix => '.txt' );
    my $f2 = $f->abs( $tmpname );
    my $sys_tmpdir = $f->sys_tmpdir;
    my $f3 = $f2->move( $sys_tmpdir )->touch;
    my $io = $f->open;
    say "Can read" if( $f->can_read );
    say "Can write" if( $f->can_write );
    say "Can execute" if( $f->can_exec );
    $f->close if( $f->opened );
    say "File is ", $f->length, " bytes big.";
    
    my $f = tempfile({ suffix => '.txt', auto_remove => 0 })->move( sys_tmpdir() );
    $f->open( '+>', { binmode => 'utf8' } );
    $f->seek(0,0);
    $f->truncate($f->tell);
    $f->append( <<EOT );
    Mignonne, allons voir si la rose
    Qui ce matin avoit desclose
    Sa robe de pourpre au Soleil,
    A point perdu cette vesprée
    Les plis de sa robe pourprée,
    Et son teint au vostre pareil.
    EOT
    my $digest = $f->digest( 'sha256' );
    $f->close;
    say $f->extension->length; # 3
    # Enable cleanup, auto removing temporary file during perl cleanup phase

    $file->utime( time(), time() );
    # or to set the access and modification time to current time:
    $file->utime;

    # Create a file object in a different OS than yours
    my $f = file( q{C:\Documents\Some\File.pdf}, os => 'Win32' );
    $f->parent; # C:\Documents\Some
    $f->filnema; # C:\Documents\Some\File.pdf

    # Get URI:
    my $u = $f->uri;
    say $u; # file:///Documents/Some/File.pdf

    # Enable globbing globally for all future objects:
    $Module::Generic::File::GLOBBING = 1;
    # or by object:
    my $f = file( "~john/some/where/file.txt", { globbing => 1 } );

    my $d = file( './some/where' );
    my @files = $d->glob( '*.pl' );
    die( "Something went wrong: ", $d->error ) if( !@files && $d->error );
    my $last_file = $d->glob( '*.pl' ) ||
    die( "Something went wrong: ", $d->error ) if( !defined( $last_file ) );
    my @all = $d->glob( '*.pl', {
        brace => 1,
        expand => 1,
        no_case => 1,
        no_magic => 1,
        sort => 1,
    });
    $d->open || die( $d->error );
    my @files = $d->read;

    my $data = $file->load_perl || die( $file->error );
    $file->unload_perl( $data, { indent => 4, max_binary_size => 1024, max_width => 60 } ) ||
        die( $file->error );

    $file->flock(1) || die( $file->error );

VERSION

    v0.5.8

DESCRIPTION

This packages provides a comprehensive and versatile set of methods and functions to manipulate files and directories. You can even manipulate filenames as if under a different OS, by providing the os parameter.

METHODS

new

Takes a file as its first parameter, whether the file actually exists or not is ok. This will instantiate an object that is used to access other key methods. It takes the following optional parameters:

autoflush

Enables or disables autoflush. Takes a boolean value and defaults to true.

auto_remove

Takes a boolean value. Automatically removes the temporary directory or file when the objects is cleaned up by perl.

base_dir

Sets the base directory for this file. If none is provided, it will attempt to get the current working directory, and if it cannot find it, most likely because it has been removed while your perl script was running, then it will try to chdir to the system temporary directory, and if that, too, fails, it will set an error return undef

base_file

Sets the base file for this file, i.e. the reference file frm which the base directory will be derived, if not already specified.

collapse

Enables or disables the collapsing of dots in the file path.

This will attempt to resolve and remove the dots to provide an absolute file path without dots. For example:

/../a/b/../c/./d.html would become /a/c/d.html

globbing

Boolean value, by default set to the value of the package variable $GLOBBING, which itself is false by default.

If enabled, this will allow "resolve" to do globbing on the filename, so that any shell meta characters are resolved. For example ~joe/some/file.txt would be resolved to /home/joe/some/file.txt

Otherwise the filename would remain ~joe/some/file.txt

This is useful when you have filename with meta characters in their file path, like /some/where/A [A-12] file.pdf

See also "globbing" to change the parameter for the current object, and also the "glob" and "resolve"

max_recursion

Sets the maximum recursion allowed. Defaults to 12.

Its value is used in "mkpath" and "resolve"

os

If provided, this will tell Module::Generic::File to treat this new file as belonging to the specified operating system. This makes it possible to manipulate files or directories as if under a different system than the one you are currently using.

Look also at "as" to change a file to make it suitable for a different OS, such as Mac, Win32, dos, Linux, etc.

resolved

A boolean flag which states whether this file has been resolved already or not.

type

The type of file this is. Either a file or a directory.

abs

If no argument is provided, this return the current object, since the underlying file is already changed into absolute file path.

If a file path is provided, then it will change it into an absolute one and return a new Module::Generic::File object.

absolute

This is a convenient alias to "abs"

append

Provided with some data as its first argument, and assuming the underlying file is a file and not a directory, this will open it if it is not already opened and append the data provided.

If the file was already opened, whatever position you were in the file, will be restored after having appended the data.

It returns the curent file object upon success for chaining or undef and sets an error object if an error occurred.

as

Provided with an OS name, and this will return a filename with a format suitable for that operating system, notwithstanding the one you are currently using.

atime

This is a shortcut to "atime" in Module::Generic::Finfo

auto_remove

This takes a boolean value and enables or disables the auto remove of temporary file or directory created by this module upon perl cleanup phase.

autoflush

This takes a boolean value and enables or disables the auto flush.

base_dir

This sets the base directory of reference for this file object.

base_file

This sets the base file of reference for this file object.

baseinfo

This returns a list containing:

1. the file base name
2. the file directory path
3. the file suffix if the file is a file or an empty string if this is a directory

In scalar context, it returns the file base name as a Module::Generic::Scalar object.

This method accepts as an optional parameter a list or an array reference of possible extensions.

basename

This returns the file base name as a Module::Generic::Scalar object.

You can provide optionally a list or array reference of possible extensions or regular expressions.

    my $f = Module::Generic::File->new( "/some/where/my/file.txt" );
    my $base = $f->basename( [qw( .zip .txt .pl )] ); # returns "file"
    my $base = $f->basename( qr/\.(.*?)$/ ); # returns "file"

binmode

Sets or get the file binmode.

block_size

This is a shortcut to "block_size" in Module::Generic::Finfo

blocking

Turns on or off blocking or non-blocking io for file opened.

blocks

This is a shortcut to "blocks" in Module::Generic::Finfo

can_append

Returns true if the file or directory are writable, and data can be added to it. False otherwise.

If an error occurred, undef will be returned an an exception will be set.

can_exec

This is an alias for "can_exec" in Module::Generic::Finfo

can_read

Returns true if the file or directory are readable. False otherwise.

If an error occurred, undef will be returned an an exception will be set.

can_write

Returns true if the file or directory are writable. False otherwise.

If an error occurred, undef will be returned an an exception will be set.

canonpath

Takes an optional parameter representing the name of the operating system for which to canonise this file path. If no operating system name is provided, this will revert to $^O. See perlvar for more information about this variable.

Returns the canon path of the file object based on the operating system specified.

changed

Returns true if the file was changed, false otherwise.

chdir

If the file object is a directory, this will attempt to "chdir" in perlfunc to it.

It returns the current file object upon success, or undef and sets an exception object if an error occurred.

child

This should be called using a directory object.

Provided with a file name (not a full path), and this will return a new file object based on the combination of the directory path and the file specified.

chmod

Provided with an octal value or a human file mode such as a+rw and this will attempt to set the file or directory mode accordingly.

It returns the current object upon success or undef and sets an exception object upon error.

chown

Provided with an uid and a gid and this will call "chown" in perlfunc on the underlying directory or file.

Both uid and gid must be provided, but you can provide a value of -1 to tell perl you do not want to change the value.

It returns true if the file or directory was changed, or o otherwise.

If an error occurred, it sets an error and return undef

See perlport for chown portability limitations.

cleanup

This is an alias for "auto_remove". It enables or disables the auto cleanup of temporary file or directory upon perl cleanup phase.

    $tmp->cleanup(1); # Enable it
    my $bool = $tmp->cleanup;

close

Close the underlying file or directory.

code

Sets or gets the http-equivalent 3-digits code describing the status of the underlying directory or file.

If a value is provided, it will set the code, but if no value is provided it will guess the code based on the file readability, existence, etc.

collapse_dots

In line with section 5.2.4 of the rfc 33986, this will flaten (i.e. remove) any dots there may be in the element file path.

It takes an optional list or hash reference of parameters, including separator which is used a directory separator. If not provided, it will revert to the default value for the current system.

contains

This can only be called using a directory object and is provided with a file or file object.

It returns true if the file is contained within the directory.

content

This method returns the content of the directory or file as a Module::Generic::Array

If this is a directory, it returns an Module::Generic::Array object with all the files within that directory, but excluding . and .. and only within that directory, so this is not recurring.

If this is a regular file, it returns its content as an Module::Generic::Array object.

If an error occurred, it returns undef and set an exception object.

content_objects

This methods works exclusively on directory object, and will return undef and set an error if you attempt to use it on anything else but a directory object.

It returns an array object of file objects. Do not use this on directory containing very large number of items for obvious reasons.

copy

Takes a dstination, and attempt to copy itself to the destination.

If the object represents a directory and the destination exists and is also a directory, it will copy the directory below the destination.

    my $d = Module::Generic::File->new( "my/other_directory" );
    my $new = $d->copy( "./another/directory" );
    # $new now represents ./another/directory/other_directory

Of course if the destination is a regular file, undef is returned and an exception is set.

If the object represents a file and the destination exists, it will copy the file under the target directory if if the destination is a directory or replace the target regular file if the destination is a regular file.

If the object file/directory does not actually exist, this merely changes virtually its file path.

This method, just like "move" relies on File::Copy, which means you can use a GLOB as the destination if you want. See File::Copy documentation for more details on this.

It returns a new Module::Generic::File object representing the new file path.

Note that you can also use the shortcut cp instead of copy

cp

Shorthand for "copy"

checksum_md5

This uses Crypt::Digest::MD5 to perform a md5 checksum as an hex value and returns it.

It requires this module Crypt::Digest::MD5 to be installed, and also the file to be a plain text file and not a directory, otherwise this sets an error and return undef

On success, this returns a md5 hex digest of the underlying file.

checksum_sha256

This uses Crypt::Digest::SHA256 to perform a sha256 checksum as an hex value and returns it.

It requires this module Crypt::Digest::SHA256 to be installed, and also the file to be a plain text file and not a directory, otherwise this sets an error and return undef

On success, this returns a md5 hex digest of the underlying file.

checksum_sha512

This uses Crypt::Digest::SHA512 to perform a sha512 checksum as an hex value and returns it.

It requires this module Crypt::Digest::SHA512 to be installed, and also the file to be a plain text file and not a directory, otherwise this sets an error and return undef

On success, this returns a md5 hex digest of the underlying file.

ctime

This is a shortcut to "ctime" in Module::Generic::Finfo

cwd

Returns a new Module::Generic::File object representing the current working directory.

delete

This will attempt to remove the underlying directory or file and returns the current object upon success or undef and set the exception object if an error occurred.

device

This is a shortcut to "device" in Module::Generic::Finfo

digest

This takes a given algorithm and returns its cryptographic digest upon success or undef and sets an error object if an error occurred.

This method can only be used if you have installed the module Digest

The supported algorithms the same ones mentionned on the documentation for Digest, which are, for example: MD5, SHA-1, SHA-256, SHA-384, SHA-512

It does not actually matter the case or whether there is or not an hyphen, so, for example, you could very well use sha256 instead of SHA-256

dirname

Returns the current element parent directory as an object.

empty

This will remove the element's content.

If the element is a directory, it will remove all element within using "rmtree" and if the element is a regular file, it will empty its content by truncating it if it is already opened, or by opening it in write mode and immediately close it.

It returns the current object upon success or undef and sets an exception object if an error occurred.

eof

Returns true when the end of file is reached, false otherwise.

exists

Returns true if the underlying directory or file exists, false otherwise.

This uses "exists" in Module::Generic::Finfo

extension

If an argument is provided, and is undefined or zero byte in length, this will remove the extension characterised with the following pattern qr/\.(\w+)$/. otherwise, if a non-empty value was provided, it will substitute any previous value for the new one and return a new Module::Generic::File object.

If no argument is provided, this simply returns the current file extension as a Module::Generic::Scalar object if it is a regular file, or an empty string if it is a directory.

Extension is simply defined with the regular expression \.(\w+)$

    my $f = file( "/some/where/file.txt" );
    my $new = $f->extension( 'pl' ); # /some/where/file.pl
    my $new = $f->extension( undef() ); # /some/where/file

Keep in mind that changing the extension of the file object does not actually alter the file on the filesystem, if any. For that you need to do something like:

    my $f2 = $f->extension( 'png' );
    $f->move( $f2 ) || die( $f->error );

Now /some/where/file.txt has been moved to /some/where/file.png on the filesystem.

extensions

In retrieval mode, this returns all extensions found as an array object.

Because the notion of "extension" is very fluid, this treats as extension anything that follows the initial dot in a filename. For example:

    my $f = Module::Generic::File->new( '/some/where/file.txt' );
    my $exts = $f->extensions;

$exts contains txt only, but:

    my $f = Module::Generic::File->new( '/some/where/file.txt.gz' );
    my $exts = $f->extensions;

$exts now contains txt and gz. And:

    my $f = Module::Generic::File->new( '/some/where/file.unknown.txt.gz' );
    my $exts = $f->extensions;

$exts would contain unknown, txt and gz. However:

    my $f = Module::Generic::File->new( '/some/where/file' );
    my $exts = $f->extensions;

$exts would be an empty array object.

If this is called on a directory, this returns an empty array object.

In assignment mode, this takes a string of one or more extensions and change the file object basename accordingly.

For example:

    my $f = Module::Generic::File->new( '/some/where/file.txt' );
    $f->extensions( 'txt.gz' );
    # $f is now /some/where/file.txt.gz

    my $f = Module::Generic::File->new( '/some/where/file.txt.gz' );
    $f->extensions( undef );
    # $f is now /some/where/file

fcntl

fdopen

Creates a new IO::Handle object based on the file's file descriptor.

filehandle

Returns the current file handle for the file/directory object by calling "handle"

If the file/directory is not opened yet, "handle" will try to open the element and return the file handle.

filename

Returns the full absolute file path to the file/directory.

If a parameter is provided, it replaces the previous value.

See also "filepath" for an alias.

fileno

Returns the element file descriptor by calling "fileno" in perlfunc

filepath

This is an alias for "filename"

find

Assuming the current object represents an existing directory, this takes an optional hash or hash reference of options followed by a code reference. This is used as a callback with the module "find" in File::Find

The callback can also be provided with the callback option.

It returns whatever "find" in File::Find returns or undef and sets an exception object if an error occurred.

The currently supported options are:

  • callback

    A code reference representing the callback called for each element found while crawling directories.

    The variable $_ representing the current file or directory found, will be made available as a Module::Generic::File object, and will also be passed as the first argument to the callback.

  • method

    The File::Find method to use to perform the search. By default this is find.

    Possible values are: find and finddepth

  • skip

    An array reference of files or directories path to skip.

    Each of the file or directories path thus provided will be converted into an Module::Generic::File with an absolute file path to avoid unpleasant surprise, since File::Find "chdir" in perlfunc into each new directory it finds.

Additional File::Find options supported. See File::Find documentation for their description.

  • bydepth

  • dangling_symlinks

  • follow

  • follow_fast

  • follow_skip

  • no_chdir

  • postprocess

  • preprocess

  • untaint

  • untaint_pattern

  • untaint_skip

finddepth

Same as "find", but using finddepth as the File::Find method instead.

finfo

Returns the current Module::Generic::Finfo object for the current element.

If a value is provided, it will replace the current Module::Generic::Finfo object.

flags

Returns the bitwise flags for the current element.

If the element is a directory, it will return 0.

This uses "fcntl" in perlfunc and F_GETFL from Fcntl to achieve the result.

It returns undef and sets an exception object if an error occurred.

flatten

This will resolve the file/directory path and remove the possible dots in its path.

It will return a new object, or undef and set an exception object if an error occurred.

flock

This is a thin wrapper around "flock" in perlfunc method of the same name.

flush

This is a thin wrapper around IO::Handle method of the same name.

As described in the IO::Handle documentation, this "causes perl to flush any buffered data at the perlio api level. Any unread data in the buffer will be discarded, and any unwritten data will be written to the underlying file descriptor. Returns 0 but true on success, undef on error."

format_write

This is a thin wrapper around IO::Handle method of the same name.

fragments

Returns an array object (Module::Generic::Array) of path fragments. For example:

Assuming the file object is: /some/where/in/time.txt

    my $frags = $f->fragments;
    # Returns: ['some', 'where', 'in', 'time.txt'];

getc

This is a thin wrapper around IO::Handle method of the same name.

This "pushes a character with the given ordinal value back onto the given handle's input stream. Only one character of pushback per handle is guaranteed."

getline

This is a thin wrapper around IO::Handle method of the same name.

"This works like <$io> described in I/O Operators in perlop except that it's more readable and can be safely called in a list context but still returns just one line. If used as the conditional within a while or C-style for loop, however, you will need to emulate the functionality of <$io> with defined($_ = $io-getline)>."

getlines

This is a thin wrapper around IO::Handle method of the same name.

"This works like <$io> when called in a list context to read all the remaining lines in a file, except that it's more readable. It will also return an error if accidentally called in a scalar context."

gid

This is a shortcut to "gid" in Module::Generic::Finfo

glob

Provided with a pattern with meta characters, or using the current object underlying filename by default, and this will call "glob" in perlfunc to resolve those meta characters, if any. For example:

~joe/some/file.txt would be resolved to /home/joe/some/file.txt

otherwise the filename would remain ~joe/some/file.txt

This is useful when you have filename with meta characters in their file path, like:

/some/where/A [A-12] file.pdf

It also accepts the following options, but only for operating systems that are not Windows, VMS or RiscOS:

Quoting, for convenience, from File::Glob

brace

"Pre-process the string to expand "{pat,pat,...}" strings like csh(1). The pattern '{}' is left unexpanded for historical reasons (and csh(1) does the same thing to ease typing of find(1) patterns)."

expand

"Expand patterns that start with '~' to user name home directories."

no_case

"By default, file names are assumed to be case sensitive; this flag makes glob() treat case differences as not significant."

no_magic

"Only returns the pattern if it does not contain any of the special characters *, ? or [." This option "is provided to simplify implementing the historic csh(1) globbing behaviour and should probably not be used anywhere else."

object

If this is false, then glob will not turn each of the files found into an Module::Generic::File object, which means the list returned will contain files as a regular string, essentially a pass-through from the results returned by "bsd_glob" in File::Glob

sort

if true, this will "sort filenames is alphabetical order (case does not matter) rather than in ASCII order."

If false, this will not sort files, which speeds up "bsd_glob" in File::Glob.

This defaults to true.

If the resulting value is empty, which means that nothing was found, it returns an empty string (not undef), otherwise, it returns a new Module::Generic::File object of the resolved file.

This method uses File::DosGlob for windows-related platforms and File::Glob for all other cases to perform globbing.

If the current file object represents a directory, the pattern provided, if any, will be expanded inside that directory.

In list context, it returns a list of all the files expanded, each one as a Module::Generic::File object, and in scalar context, it returns the last file expanded, also as a Module::Generic::File object.

If you call glob in list context, but do not want all the files found to be turned into Module::Generic::File objects, then pass the option object with a false value.

Example:

    use Module::Generic::File qw( file );
    my $d = file( './some/where/' );
    my @files = $d->glob( '*.pl' );
    die( "Something went wrong: ", $d->error ) if( !@files && $d->error );
    my $last_file = $d->glob( '*.pl' ) ||
    die( "Something went wrong: ", $d->error ) if( !defined( $last_file ) );
    my @all = $d->glob( '*.pl', {
        brace => 1,
        expand => 1,
        no_case => 1,
        no_magic => 1,
        sort => 1,
    });
    my $new_file = $file->glob( './some/where/*.pl' );

globbing

Set or get the boolean value of the current object.

If enabled, globbing will be enabled and this will have the effect of performing "glob" upon resolving the filename.

Returns the current boolean value.

gobble

Assuming this is object represents a regular file, this will return its content as a regular string.

If the object represents a directory, it will return undef.

See also "load"

gush

This does thd countrary of "gobble". It will outpour the data provided into the underlying file element.

This only works on file object and if a directory object is used, this will do nothing and merely return the current object used.

See also "unload"

handle

Returns the current file/directory handle if it is already opened, or attempts to open it.

It will return undef and set an exception object if an error occurred.

has_valid_name

This optionally takes a file name, or default to the underlying object file base name, and checks if it contains any illegal characters.

It returns true if it is clean or false otherwise.

The regular expression used is: [\x5C\/\|\015\012\t\013\*\"\?\<\:\>]

inode

This is a shortcut to "inode" in Module::Generic::Finfo

ioctl

This is a thin wrapper around IO::Handle method of the same name.

is_absolute

Returns true if the element is an absolute path or false otherwise.

is_dir

Returns true if the element is a directory or false otherwise.

is_directory

This is an alias for "is_dir"

is_empty

Returns true if the element is empty or false otherwise.

If the element is a directory empty means there is no file or directory within.

If the element is a regular file, empty means it is zero byte big.

is_file

Returns true if the element is regular file or false otherwise.

Returns true if the element is symbolic link or false otherwise.

is_opened

Alias to "opened"

is_part_of

Provided with a directory path or a Module::Generic::File object representing a directory and this returns true if the current element is part of the provided directory path, or false otherwise.

It returns undef and set an exception object if an error occurred.

is_relative

Returns true if the current element path is relative or false otherwise.

is_rootdir

Returns true if the current element represents the system root directory, such as / under Linux system or, for example, C:\\ under windows or false otherwise.

iterator

Assuming the current element is a directory, this method takes a code reference as a callback whicih will be called for every element found inside the directory.

It takes a list or an hash reference of optional parameters:

recurse

If true, this method will traverse the directories within recursively.

If true, the symbolic link will be resolved and followed.

The returned value from the callback is ignored.

join

Takes a list or an array reference of path fragments and this returns a new Module::Generic::File object.

It does not use nor affect the current object used and it can actually be called as a class method. For example:

    my $f = Module::Generic::File->join( qw( this is here.txt ) );
    # Returning a file object for /this/is/here.txt or maybe on Windows C:\\this\is\here.txt
    my $f = Module::Generic::File->join( [qw( this is here.txt )] ); # works too
    my $f2 = $f->join( [qw( new path please )] ); # works using an existing object
    # Returns: /new/path/please

last_accessed

This is a shortcut to "atime" in Module::Generic::Finfo

last_modified

This is a shortcut to "mtime" in Module::Generic::Finfo

length

This returns the size of the element as a Module::Generic::Number object.

if the element does not yet exist, Module::Generic::Number object representing the value 0 is returned.

This uses "size" in Module::Generic::Finfo

line

Provided with a callback as a subroutine reference or anonymous subroutine, and this will call the callback passing it each line of the file.

If the callback returns undef, this will terminate the browsing of each line, unless the option auto_next is set. See below.

It takes some optional arguments as follow:

chomp boolean

If true, each line will be "chomp" in perlfunc'ed before being passed to the callback.

auto_next boolean

If true, this will ignore the return value from the callback and will move on to the next line.

lines

Assuming this is a regular file , this methods returns its content as an array object (Module::Generic::Array) of lines.

If a directory object is called, or the element does not exist or the file element is not readable, this still returns the array object, but empty.

If an error occurred, undef is returned and an exception is set.

This method takes an optional hash or hash reference of parameters, which is passed to the "open" method when opening the file.

Also the additional following parameters are recognised:

chomp
    # will perform a regular chomp
    my $array = $f->lines( chomp => 1 );
    # will do a chomp after setting locally $/ to \r\n
    my $array = $f->lines( chomp => 'windows' );
    # will do a chomp (not a regular expression) for both unix and window system types
    my $array = $f->lines( chomp => 'unix|windows' );
    my $array = $f->lines( chomp => qr/[\r]/ );
    my $array = $f->lines({ chomp => 1 });
    my $array = $f->lines({ chomp => windows });
    my $array = $f->lines({ chomp => 'unix|windows' });
    my $array = $f->lines({ chomp => qr/[\r]/ });

This can be either just a string, a true value or a regular expression, for example using "qr" in perlfunc

If a regular expression is provided, it will be used to weed out end of line carriage returns (multiple times) that will be captured using this regular expression you provide explicitly.

Otherwise, if you merely provide a true value, such as 1, then, by default, this will use "chomp" in perlfunc and remove the trailing new line based on the value of $/.

If the value of chomp is windows or macos (i.e. MacOS v9, the old one) or unix, then this will set a local value of $/ to the corresponding line feed and carriage return sequence, typically \r\n for Windows and \r for MacOS and \n for unix and then call "chomp" in perlfunc. This is very fast, but will remove only the specific sequence. This means if you have a line such as:

    Double whammy\r

But you call "lines" as:

    my $lines = $f->lines( chomp => 'windows' );

It will not work, because Windows sequence is \r\n, so here you would need to use mac instead.

Also the following line:

    Double whammy\n\n

Then, you are on a Linux system and call:

    my $lines = $f->lines( chomp => 1 );

This will return:

    Double whammy\n

Because "chomp" in perlfunc only remove one sequence. If you want to remove all occurrences, you need to specify your regular expression.

    my $lines = $f->lines( chomp => qr/[\r\n]/ );

And this will be applied on each line for multiple occurrences, but note that on large file, it will be slow.

Alternatively you can provide more than one os by separating them with a pipe (|), such as:

    my $lines = $f->lines( chomp => 'unix|windows' );

Supported os names are: aix, amigaos, beos, darwin, dos, freebsd, linux, netbsd, openbsd, mac, macos, macosx, mswin32, os390, os400, riscos, solaris, sunos, symbian, unix, vms, windows, and win32

load

Assuming this element is an existing file, this will load its content and return it as a regular string.

If the binmode used on the file is :unix, then this will call "read" in perlfunc to load the file content, otherwise it localises the input record separator $/ and read the entire content in one go. See "$INPUT_RECORD_SEPARATOR" in perlvar

If this method is called on a directory object, it will return undef.

load_json

This will load the file data, which is assumed to be json in utf8, then decode it using JSON and return the resulting perl data.

This requires the JSON module to be installed or it will set an error and return undef.

If an eror occurs during decoding, this will set an error and return undef.

load_perl

This will load perl's data structure from file using "do" in perlfunc and return the resulting perl data.

It sets an error and returns undef if an error occurred.

load_utf8

This does the same as "load", but ensure the binmode used is :utf8 before proceeding.

lock

This method locks the file.

It takes either a numeric argument representing the flag bitwise, or a list or hash reference of optional parameters, such as:

exclusive

This will add the bit of Fcntl::LOCK_EX

shared

This will add the bit of Fcntl::LOCK_SH

non_blocking or nb

This will add the bit of Fcntl::LOCK_NB

unlock

This will add the bit of Fcntl::LOCK_UN

timeout

Takes an integer used to set an alarm for the lock. If a lock cannot be obtained before the timeout, an error is returned.

This returns the current object upon success or undef and set an exception object if an error occurred.

locked

Returns true if the file is locked. More specifically, this returns the value of the flags originally used to lock the file.

mkdir

Creates the directory represented by the file object. This will fail if the parent directory does not exist, so this does not create a path. For that check "makepath"

It returns true upon success and undef upon failure. The error, if any, can be retrieved with error

makepath

This is an alias to "mkpath"

max_recursion

Sets or gets the maximum recursion limit.

mkpath

This takes a code reference that is used as a callback.

It will create the path corresponding to the element, or to the list of path fragments provided as optional arguments.

For each path fragments, this will call the callback and provided it with an hash reference containing the following keys:

dir

The current path fragment as a regular string

parent

The current parent full path as a string

path

The current full path as a regular string

volume

On Windows, this would contain the volume name as a string.

For example:

    my $f = Module::Generic::File->new( "/my/directory/file.txt" );
    # Assuming the directories in this example do not exist at all
    $f->mkpath(sub
    {
        my $ref = shift( @_ );
        # $ref->{dir} would contain 'my'
        # $ref->{path} would contain '/my'
        # $ref->{parent} would contain '/'
        # $ref->{volume} would be empty
    });

It returns an array object (Module::Generic::Array) of all the path fragments.

If an error occurred, this returns undef and set an exception object.

mmap

    use Module::Generic::File qw( tempfile );
    my $file = tempfile({ unlink => 1 });
    $file->mmap( my $var, 10240, '+<' );
    # or
    $file->mmap( my $var, 10240 );
    # or; the size will be derived from the size of the variable $var content
    $file->mmap( my $var );
    # then:
    $var = "Hello there";
    $var =~ s/Hello/Good bye/;

With fork:

    use Module::Generic::File qw( tempfile );
    use POSIX ();
    use Storable::Improved ();
    
    my $file = tempfile({ unlink => 1 });
    $file->mmap( my $result, 10240, '+<' );
    # Block signal for fork
    my $sigset = POSIX::SigSet->new( POSIX::SIGINT );
    POSIX::sigprocmask( POSIX::SIG_BLOCK, $sigset ) || 
        die( "Cannot block SIGINT for fork: $!\n" );
    my $pid = fork();
    # Parent
    if( $pid )
    {
        POSIX::sigprocmask( POSIX::SIG_UNBLOCK, $sigset ) || 
            die( "Cannot unblock SIGINT for fork: $!\n" );
        if( kill( 0 => $pid ) || $!{EPERM} )
        {
            # Blocking wait; use POSIX::WNOHANG for non-blocking wait
            waitpid( $pid, 0 );
            print( "Exit value: ", ( $? >> 8 ), "\n" );
            print( "Signal: ", ( $? & 127 ), "\n" );
            print( "Has core dump? ", ( $? & 128 ), "\n" );
        }
        else
        {
            print( "Child $pid already gone\n" );
        }
        my $object = Storable::Improved::thaw( $result );
    }
    elsif( $pid == 0 )
    {
        # Do some work
        my $object = My::Package->new;
        $result = Storable::Improved::freeze( $object );
    }
    else
    {
        if( $! == POSIX::EAGAIN() )
        {
            die( "fork cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the child.\n" );
        }
        elsif( $! == POSIX::ENOMEM() )
        {
            die( "fork failed to allocate the necessary kernel structures because memory is tight.\n" );
        }
        else
        {
            die( "Unable to fork a new process: $!\n" );
        }
    }

Provided with some option parameters and this will create a mmap. Mmap are powerful in that they can be used and shared among processes including fork, but excluding threads. Of course, it you want to share objects or other less simple structures, you need to use serialisers like Storable::Improved or Sereal.

If the file is not opened yet, this will open it using the mode specified, or +< by default. If the file is already opened, an error will be returned that the file cannot be opened by mmap because it is already opened.

If your perl version is greater or equal to v5.16.0, then it will use perl native PerlIO, otherwise if you have File::Map installed, it will use it as a substitute.

You can force this method to use File::Map by either setting the global package variable $MMAP_USE_FILE_MAP to true, or the object property "use_file_map" to true.

If File::Map is used, you can call "unmap" to terminate the tie, but you should not need to do it since File::Map does it automatically for you. This is not necessary if you are using perl's native mmap

The options parameters are:

1. variable

A variable that will be tied to the file object.

2. size

The maximum size of the variable allocated in the mmap'ed file. If this not provided, then the size will be derived from the size of the variable, or if the variable is not defined or empty, it will use the package global variable $DEFAULT_MMAP_SIZE, which is set to 10Kb (10240 bytes) by default.

For those with a perl version lower than 5.16.0, be careful that if you use more than the size allocated, this will raise an error with File::Map. With PerlIO there is no such restriction.

3. mode

The mode in which to mmap open the file. Possible modes are the same as with open, however, mmap will not work if you chose a mode like: >, +>, >> or +>>, thus if you want to mmap the file in read only, use < and if you want read-write, use +<. You can also use letters, such as r for read-only and r+ for read-write.

The mode can be accompanied by a PerlIO layer like :raw, which is the default, or :encoding(utf-8), but note that while PerlIO mmap, if your perl version is greater or equal to v5.16.0, will work fine with utf-8, File::Map warns of possibly unknown results when using utf-8 encoder. So if your perl version is equal or greater than 5.16.0 you are safe, but otherwise, be careful if all works as you expect. Of course, if you use serialisers like Storable::Improved or Sereal, then you should not use an encoding, or at least use :raw, which, again, is the default for File::Map

See also BSD documentation for mmap

mode

This is a shortcut to "mode" in Module::Generic::Finfo

move

This behaves exactly like "copy" except it moves the element instead of copying it.

Note that you can use mv as a method shortcut instead.

mtime

This is a shortcut to "mtime" in Module::Generic::Finfo

mv

Shorthand for "move"

This is a shortcut to "nlink" in Module::Generic::Finfo

open

This takes an optional mode or defaults to <

Other valid mode can be >, +>, >>, +<, w, w+, r+, a, a+, < and r or an integer representing a bitwise value such as O_APPEND, O_ASYNC, O_CREAT, O_DEFER, O_EXCL, O_NDELAY, O_NONBLOCK, O_SYNC, O_TRUNC, O_RDONLY, O_WRONLY, O_RDWR. For example: O_WRONLY|O_APPEND For that see Fcntl

Provided with an optional list or hash reference of parameters and this will open the underlying element.

Possible options are:

autoflush

Takes a boolean value

binmode

The binmode value, with or without the semi colon before, such as utf8 or binary

lock

If true, this will set a lock based on the mode in which to open the file.

For example, opening the file in write or append mode, will lead to an exclusive lock while opening the file in read mode will lead to a shared lock.

truncate

If true, this will truncate the file after opening it.

open_bin

This opens the file using binmode value of :raw

open_utf8

This opens the file using binmode value of :utf8

opened

Returns the current element file handle if it is opened or a smart null value using "new_null" in Module::Generic

"new_null" in Module::Generic will return a sensitive null based on the caller's expectations. Thus if the caller expects an hash reference, "new_null" in Module::Generic would return an empty hash reference.

parent

Returns the parent element of the current object.

print

Calls "print" in perlfunc on the file handle and pass it whatever arguments is provided.

printf

Calls "printf" in perlfunc on the file handle and pass it whatever arguments is provided.

printflush

This is a thin wrapper around IO::Handle method of the same name.

"Turns on autoflush, print ARGS and then restores the autoflush status of the IO::Handle object. Returns the return value from print."

println

Calls "say" in perlfunc on the file handle and pass it whatever arguments is provided.

rdev

This is a shortcut to "rdev" in Module::Generic::Finfo

read

If the element is a directory, this will call "read" in IO::Dir and return the value received.

If it is called in list context, then this will return an array of all the directory elements, otherwise, this will return one directory element.

If the option as_object is provided and set to a true value, that element will be returned as an Module::Generic::File object.

If this is called in list context and the option exclude_invisible is provided and set to a true value, the array of directory elements returned will exclude any element that starts with a dot.

If the element is a regular file, then it takes the same arguments as "read" in perlfunc, meaning:

    $io->read( $buff, $size, $offset );
    # or
    $io->read( $buff, $size );
    # or
    $io->read( $buff );

If an error occurred, this returns undef and set an exception object.

readdir

This is an alias to "read", but can only be called on a directory, or it will return an error.

This calls "readlink" in perlfunc and returns a new Module::Generic::File object, but this does nothing and merely return the current object if the current operating system is one of Win32, VMS, RISC OS, or if the underlying file does not actually exist or of course if the element is actually not a symbolic link.

If an error occurred, this returns undef and set an exception object.

relative

Provided a base directory or using "base_dir" by default and this returns a relative path representation of the current element, as a new Module::Generic::File object.

rename

This is an alias for "move"

remove

This is an alias for "delete"

resolve

Provided with a path and a list or hash reference of optional parameters and this will attempt at resolving the file path.

It returns a new Module::Generic::File object or undef and sets an exception object if an error occurred.

The parameter supported are:

glob

A boolean, which, if true, will use "glob" in perlfunc to resolve any meta characters.

If glob is turned on and the glob results into an empty string, implying nothing was found, then this will set an error with code 404 and return undef.

If no glob parameter is provided, this reverts to the globbing property of the object set upon instantiation.

See "glob" for more information and "new" for the globbing object property.

recurse

If true, this will have resolve perform recursively.

resolved

Returns true if the file object has been resolved or false otherwise.

rewind

This will call "rewind" in perlfunc on the file handle.

rewinddir

This will call "rewinddir" in IO::Dir on the directory file handle.

rmdir

Removes the directory represented by ths object. It silently ignores and return the current object if it is called ona a file object.

If the directory is not empty, this will set an error and return undef.

If all goes well, it returns the value returned by "rmdir" in perlfunc

root_dir

This returns an object representation of the system root directory.

rootdir

This is an alias for "root_dir"

This is also a class function that can be imported.

say

This will call "say" in perlfunc on the file handle.

seek

This will call "seek" in perlfunc on the file handle.

size

Provided with an optional list or hash reference of parameters and this returns the size of the underlying element.

Option parameters are:

follow_link

If true, links will be followed in calculating the size of a directory. This defaults to false.

Besides the above parameters, you can use the same parameters than the ones used in File::Find, namely: bydepth, dangling_symlinks, follow, follow_fast, follow_skip, no_chdir, postprocess, preprocess, untaint, untaint_pattern and untaint_skip.

For more information see "%options" in File::Find

This method returns a new Module::Generic::Number object representing the total size, or undef and set an exception object if an error occurred.

slurp

This is an alias for "load" It is there, because the name as a method is somewhat popular.

slurp_utf8

This is an alias for "load_utf8"

spew

This is an alias for "unload"

spew_utf8

This is an alias for "unload_utf8"

split

This does the reverse of "join" and will return an array object (Module::Generic::Array) representing the path fragments of the underlying object file or directory. For example:

    # $f is /some/where/in/time.txt
    my $frags = $f->split;
    # Returns ['', 'some', 'where', 'in', 'time.txt']

It can take an optional hash or hash reference of parameters. The only one currently supported is remove_leading_sep, which, if true, will skip the first entry of the array:

    my $frags = $f->split( remove_leading_sep => 1 );
    # Returns ['some', 'where', 'in', 'time.txt']

spurt

This is an alias for "unload"

spurt_utf8

This is an alias for "unload_utf8"

stat

Returns the value from "finfo"

stderr

This returns a filehandle object referencing STDERR. It takes an optional hash or hash reference of following options:

autoflush

This takes a boolean value. If true, auto flushing will be enabled on this filehandle, otherwise, if false, it will be disabled.

binmode

This takes the same value as you would provide to "binmode" in perlfunc

You can import this function into your namespace, such as:

    use Module::Generic::File qw( stderr );
    my $io = stderr;
    # etc...

Or you can also call it from another Module::Generic::File object:

    use Module::Generic::File qw( file );
    my $f = file( $some_file_name );
    my $err = $f->stderr;

stdin

This returns a filehandle object referencing STDIN. It takes an optional hash or hash reference of following options:

autoflush

This takes a boolean value. If true, auto flushing will be enabled on this filehandle, otherwise, if false, it will be disabled.

binmode

This takes the same value as you would provide to "binmode" in perlfunc

You can import this function into your namespace, such as:

    use Module::Generic::File qw( stdin );
    my $io = stdin;
    # etc...

Or you can also call it from another Module::Generic::File object:

    use Module::Generic::File qw( file );
    my $f = file( $some_file_name );
    my $in = $f->stdin;

stdout

This returns a filehandle object referencing STDOUT. It takes an optional hash or hash reference of following options:

autoflush

This takes a boolean value. If true, auto flushing will be enabled on this filehandle, otherwise, if false, it will be disabled.

binmode

This takes the same value as you would provide to "binmode" in perlfunc

You can import this function into your namespace, such as:

    use Module::Generic::File qw( stdout );
    my $io = stdout;
    # etc...

Or you can also call it from another Module::Generic::File object:

    use Module::Generic::File qw( file );
    my $f = file( $some_file_name );
    my $out = $f->stdout;

Provided with a file path or an Module::Generic::File object, and this will call "symlink" in perlfunc to create a symbolic link.

On the following operating system not supported by perl, this will merely return the current object itself: Win32 and RISC OS

This returns the current object upon success and undef and sets an exception object if an error occurred.

sync

This is a thin wrapper around IO::Handle method of the same name.

""sync" synchronizes a file's in-memory state with that on the physical medium. "sync" does not operate at the perlio api level, but operates on the file descriptor (similar to "sysread" in perlfunc, "sysseek" in perlfunc and "systell" in perlfunc). This means that any data held at the perlio api level will not be synchronized. To synchronize data that is buffered at the perlio api level you must use the flush method. "sync" is not implemented on all platforms. Returns 0 but true on success, undef on error, undef for an invalid handle. See fsync(3c)."

sysread

This is a thin wrapper around IO::Handle method of the same name.

sysseek

This is a thin wrapper around IO::Handle method of the same name.

syswrite

This is a thin wrapper around IO::Handle method of the same name.

tell

Calls "tell" in perlfunc on the current element file handle, passing it whatever information was provided.

tmpdir

This method returns a temporary directory object.

It takes an optional list or hash reference of parameters:

cleanup

Takes a boolean value.

If true, this will enable the auto-remove feature of the directory object. See "auto_remove"

See also unlink

dir

Takes a string representing an existing directory.

If provided, this will instruct this method to create the temporary directory below this directory.

tmpdir

Takes a boolean value.

If true, the temporary directory will be created below the system wide temporary directory. This system temporary directory is taken from "tmpdir" in File::Spec

Takes a boolean value.

If true, this will enable the auto-remove feature of the directory object. See "auto_remove"

See also cleanup

Upon success, this returns a new Module::Generic::File object representing the new temporary directory, or if an error occurred, it returns undedf and sets an exception object.

tmpnam

This is an alias for "tmpname"

tmpname

This returns the basename of a new temporary directory object.

touch

This method mirrors the command line utility of the same name and is to be used for a file object.

It creates the file with no content if it does not already exist. If the file exists, it merely update its modification time.

It returns the current object upon success, or undef and sets an exception object if an error occurred.

touchpath

This is a variation from "touch" in that it will create the path leading to the underlying file object, and then "touch" the file to create it.

It returns the current object upon success, or undef and sets an exception object if an error occurred.

truncate

This will call "truncate" on the file handle of the underlying file object.

type

Returns the type of element this object represents. It can be either file or directory.

If there is no value set, this will try to guess it.

uid

This is a shortcut to "uid" in Module::Generic::Finfo

ungetc

This is a thin wrapper around IO::Handle method of the same name.

"Pushes a character with the given ordinal value back onto the given handle's input stream. Only one character of pushback per handle is guaranteed."

unlink

This will attempt to remove the underlying file.

It will return undef and set an exception object if this method is called on a directory object.

It returns the current object upon success, or undef and sets an exception object if an error occurred.

unload

Provided with some data in the first parameter, and a list or hash reference of optional parameters and this will add this data to the underlying file element.

The available options are:

append

If true and assuming the file is not already opened, the file will be opened using >> otherwise > will be used.

lock

If true, "unload" will perform a lock after opening the file and unlock it before closing it.

Other options are the same as the ones used in "open"

It returns the current object upon success, or undef and sets an exception object if an error occurred.

unload_json

Provided some perl data and an optional hash or hash reference of options and this will encode those data and save it as utf8 data to the file.

If the JSON module is not installed or an error occurs during JSON encoding, this sets an error and returns undef.

The JSON object provided by "new_json" in Module::Generic already has the following options enabled: allow_nonref, allow_blessed, convert_blessed and relaxed

Supported options are as follows, including any of the JSON supported options:

allow_blessed

Boolean. When enabled, this will not return an error when it encounters a blessed reference that JSON cannot convert otherwise. Instead, a JSON null value is encoded instead of the object.

allow_nonref

Boolean. When enabled, this will convert a non-reference into its corresponding string, number or null JSON value. Default is enabled.

allow_tags

Boolean. When enabled, upon encountering a blessed object, this will check for the availability of the FREEZE method on the object's class. If found, it will be used to serialise the object into a nonstandard tagged JSON value (that JSON decoders cannot decode).

allow_unknown

Boolean. When enabled, this will not return an error when JSON encounters values it cannot represent in JSON (for example, filehandles) but instead will encode a JSON "null" value.

ascii

Boolean. When enabled, will not generate characters outside the code range 0..127 (which is ASCII).

canonical or ordered

Boolean value. If true, the JSON data will be ordered. Note that it will be slower, especially on a large set of data.

convert_blessed

Boolean. When enabled, upon encountering a blessed object, JSON will check for the availability of the TO_JSON method on the object's class. If found, it will be called in scalar context and the resulting scalar will be encoded instead of the object.

indent

Boolean. When enabled, this will use a multiline format as output, putting every array member or object/hash key-value pair into its own line, indenting them properly.

latin1

Boolean. When enabled, this will encode the resulting JSON text as latin1 (or iso-8859-1),

max_depth

Integer. This sets the maximum nesting level (default 512) accepted while encoding or decoding. When the limit is reached, this will return an error.

pretty

Boolean value. If true, the JSON data will be generated in a human readable format. Note that this will take considerably more space.

space_after

Boolean. When enabled, this will add an extra optional space after the ":" separating keys from values.

space_before

Boolean. When enabled, this will add an extra optional space before the ":" separating keys from values.

utf8

Boolean. This option is ignored, because the JSON data are saved to file using UTF-8 and double encoding would produce mojibake.

unload_perl

Just like "unload", this takes some perl data structure (most likely an hash or an array), and some options passed as a list or as an hash reference and will open the file using :utf8 for "binmode" in perlfunc and save the perl data structure to it using Data::Dump

If Data::Dump is not installed, this will return an error.

The following options are supported:

indent

Integer. This is the number of spaces to use as indentation of lines. By default, Data::Dump uses 2 spaces.

max_binary_size

Integer. This is the size threshold of binary data above which it will be converted into base64.

max_width

Integer. This is the line width threshold after which a new line will be inserted by Data::Dump

unload_utf8

Just like "unload", this takes some data and some options passed as a list or as an hash reference and will open the file using :utf8 for "binmode" in perlfunc and save the data to it.

unlock

This will unlock the underlying file if it was locked.

It returns the current object upon success, or undef and sets an exception object if an error occurred.

unmap

    $file->unmap( $var ) || die( $file->error );

Untie the previously tied variable to the file object. See "mmap"

This is useful only if you are using File::Map, which happens if your perl version is lower than 5.16.0 or if you have set the global package variable MMAP_USE_FILE_MAP to a true value, or if you have set the file object property "use_file_map" to a true value.

uri

Returns a URI file object, such as file:///Documents/Some/File.pdf

use_file_map

Set or get the boolean value for using File::Map in the "mmap" method. By default, the value is taken from the package global variable $MMAP_USE_FILE_MAP, and also by default if your perl version is greater or equal to v5.16.0, then "mmap" will use ":mmap" in PerlIO. By setting this to true, you can force L/mmap> to use File::Map rather than ":mmap" in PerlIO

It returns the current file object upon success, or undef and sets an error object upon failure.

utime

Provided with an optional access time and modification time as unix timestamp value, i.e. 10 digits representing the number of seconds elapsed since epoch, and this will change the access and modification time of the underline file or directory. For example:

    $f->utime( time(), time() );
    # is same, on most system, as:
    $f->utime;

Quoting "utime" in perlfunc, "if the first two elements of the list are undef, the utime(2) syscall from your C library is called with a null second argument. On most systems, this will set the file's access and modification times to the current time"

It returns the value returned by the core utime function, which is true if the file was changed, and false otherwise.

volume

Sets or gets the volume of the underlying file or directory. This is only applicable under windows.

write

Provided with some data and this will add them to the underlying file element.

It will merely return the current object if this is a directory element, and it will return undef and set an exception object if the file is not opened.

It returns the current object upon success, or undef and sets an exception object if an error occurred.

For example:

    $f->open;
    $f->write( $data );
    $f->write( @list_of_data );
    # or
    $f->open->write( $data );

CLASS FUNCTIONS

cwd

Returns the current working directory by calling "cwd" in URI::file

file

Takes a string, an optional hash reference of parameters and returns an Module::Generic::File object.

It can be called the following ways:

    file( $file_obj );
    file( $file_obj, $options_hash_ref );
    file( $file_obj, %options );

    $obj->file( $file_obj );
    $obj->file( $file_obj, $options_hash_ref );
    $obj->file( $file_obj, %options );

    $obj->file( '/some/file' );
    $obj->file( '/some/file', $options_hash_ref );
    $obj->file( '/some/file', %options );
    $obj->file( $stringifyable_object );
    $obj->file( $stringifyable_object, $options_hash_ref );
    $obj->file( $stringifyable_object, %options );

    file( "/some/file.txt" );
    file( "./my/directory" );

rmtree

This takes a path, or an Module::Generic::File object and some optional parameters as a list or as an hash reference and removes the underlying path, whether it contains elements within or not. So this is a recursive removal of all element within the given directory path. Thus, it must be called on a directory object.

It takes the following optional parameters:

dry_run

If true, this will only pretend to remove the files recursively. This is useful for testing without actually removing anything.

keep_root

If true, then "rmtree" will keep the directory and remove all of its content. If false, it will also remove the directory itself on top of its content. Defaults to false.

max_files

Set the maximum numberof file beyond which this function will refuse to perform.

This is useful, if you know you expect only a certain number of files within a directory and you do not want the program to hang, or possibly you do not want it to removethe directory because too many files within would be a sign of an error, etc.

You can also pass other parameters such as the one used by File::Find, namely: bydepth, dangling_symlinks, follow, follow_fast, follow_skip, no_chdir, postprocess, preprocess, untaint, untaint_pattern and untaint_skip

See "%options" in File::Find for more information.

Example of usage:

    $obj->rmtree( $some_dir_path );
    $obj->rmtree( $some_dir_path, $options_hashref );
    Module::Generic::File->rmtree( $some_dir_path );
    Module::Generic::File->rmtree( $some_dir_path, $options_hashref );
    rmtree( $some_dir_path );
    rmtree( $some_dir_path, $options_hashref );
    file( $some_dir_path )->rmtree;

Upon success it returns the current object. If it was called as a class function, an object is created, and it will be returned upon success too.

It returns undef and set an exception object if this is called on a file object.

rootdir

This returns an object representation of the system root directory.

sys_tmpdir

Returns a new Module::Generic::File object representing the path to the system temporary directory as returned by "tmpdir" in File::Spec

tempdir

Returns a new Module::Generic::File object representing a unique temporary directory.

tempfile

Returns a new Module::Generic::File object representing a unique temporary file.

It takes the following optional parameters:

cleanup

If true, this will enable the auto-remove option of the object. See "auto_remove"

See also unlink which is an alias.

dir

A directory path to be used to create the temporary file within.

This parameter takes precedence over tmpdir

mode

This is the mode used to open this temporary file. It is used as arguement to "open"

open

If true, the temporary file will be opened. It defaults to false.

suffix or extension

A suffix to add to the temporary file including leading dot, such as .txt. You can also specify the extension without any leading dot, such as txt

tmpdir

The path or object of a directory within which to create the temporary file.

See also dir

unlink

If true, this will enable the auto-remove option of the object. See "auto_remove"

See also cleanup which is an alias.

EXCEPTION

This module does not croak or die (at least not intentionally) as a design under the belief that it is up to the main code of the script to control the flow and any interruptions.

When an error occurrs, the methods under this package will return undef and set an Module::Generic::Exception object that can be retrieved using the inherited "error" in Module::Generic method.

For example:

    my $f = Module::Generic::File->new( "/my/file.txt" );
    $f->open || die( $f->error );

However, "error" in Module::Generic used to return undef, is smart and knows in a granular way (thanks to Want) the context of the caller. Thus, if the method is chained, "error" in Module::Generic will instead return a Module::Generic::Null object to allow the chaining to continue and avoid the perl error that would have otherwise occurred: "method called on an undefined value"

OVERLOADING

Objects of this package are overloaded and their stringification will call "filename"

SERIALISATION

Serialisation by CBOR, Sereal and Storable::Improved (or the legacy Storable) is supported by this package. To that effect, the following subroutines are implemented: FREEZE, THAW, STORABLE_freeze and STORABLE_thaw

VIRTUALISATION

This module has this unique feature that enables you to work with files in different operating system context. For example, assuming your environment is a unix flavoured operating system, you could still do this:

    use Module::Generic::File qw( file );
    my $f = file( q{C:\Documents\Newsletters\Summer2018.pdf}, os => 'win32' );
    $f->parent; # C:\Documents\Newsletters

Then, switch to old Mac format:

    my $f2 = $f->as( 'mac' );
    say $f2; # Documents:Newsletters:Summer2018.pdf

Those files manipulation under different os, of course, have limitation since you cannot use real filesystem related method like open, print, etc, on, say a win32 based file object in a Unix environment, as it would not work.

AUTHOR

Jacques Deguest <jack@deguest.jp>

SEE ALSO

Module::Generic::Finfo, Module::Generic, Module::Generic::Exception, Module::Generic::Number, Module::Generic::Scalar, Module::Generic::Array, Module::Generic::Null, Module::Generic::Boolean

COPYRIGHT & LICENSE

Copyright (c) 2021 DEGUEST Pte. Ltd.

You can use, copy, modify and redistribute this package and associated files under the same terms as Perl itself.