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 );
    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 );
    $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

VERSION

    v0.1.11

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.

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

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_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.

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"

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

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 one parameter which must be a code reference. This is used as a callback with the module "find" in File::Find

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

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.

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 croak() if accidentally called in a scalar context."

gid

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

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.

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_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_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.

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_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.

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 ();
    
    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::thaw( $result );
    }
    elsif( $pid == 0 )
    {
        # Do some work
        my $object = My::Package->new;
        $result = Storable::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 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 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 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.

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

Returns a relative path representation of the current element.

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 only parameter supported is:

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"

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.

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_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

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

A suffix to add to the temporary file including 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"

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.