File::...Manual(3pm)
๐ File::Util::Manual ๐ โ User Contributed Perl Documentation, 3pm
โจ NAME โจ
File::Util::Manual โ File::Util Reference
๐ธ VERSION ๐ธ
version 4.201720
๐ฆ INTRODUCTION ๐ฆ
Okay so this manual is, like, the complete reference to every public method you can use in File::Util. It also touches on a few other topics, as set forth below.
For a "nutshell"-type reference full of actual small example code snippets, go look at File::Util::Manual::Examples.
For examples of full Programs using File::Util, go look at File::Util::Cookbook.
๐ The layout of the Manual ๐
Now we'll start out with some brief notes about what File::Util is (and isn't), then we'll talk about the syntax used in File::Util. After that we discuss custom error handling and diagnostics in File::Util. Finally, the rest of this document will cover File::Util's object methods, one by one, with brief usage examples.
๐ What File::Util Is ๐
File::Util is a "Pure Perl" library that provides you with several easy-to-use tools to wrangle files and directories. It has higher order methods (that's fancy talk for saying that you can feed subroutine references to some of File::Util's object methods and they will be treated like "callbacks").
File::Util is mainly Object-Oriented Perl, but strives to be gentle and accommodating to those who do not know about or who do not like "OO" interfaces. As such, many of the object methods available in File::Util can also be imported into your namespace and used like regular subroutines to make short work of simple tasks.
For more advanced tasks and features, you will need to use File::Util's object-oriented interface. Don't worry, it's easy, and there are plenty of examples here in the documentation to get you off to a great and productive start. If you run into trouble, help is available.
File::Util tries its best to adhere to these guiding principles:
๐ Be easy ๐
Make hard things easier and safer to do while avoiding common mistakes associated with file handling in Perl. Code using File::Util will automatically be abiding by best practices with regard to Perl IO.
File::Util makes the right decisions for you with regard to all the little details involved in the vast majority of file-related tasks. File locking is automatically performed for you! File handles are always lexically scoped. Safe reads and writes are performed with hard limits on the amount of RAM you are allowed to consume in your process per file read. (You can adjust the limits.)
๐ง Be portable ๐ง
We make sure that File::Util is going to work on your computer or virtual machine. If you run Windows, Mac, Linux, BSD, some flavor of Unix, etc... File::Util should work right out of the box. There are currently no platforms where Perl runs that we do not support. If Perl can run on it, File::Util can run on it. If you want unicode support, however, you need to at least be running Perl 5.8 or better.
๐ Be compatible ๐
File::Util has been around for a long time, and so has Perl. We'd like to think that this is because they are good things! This means there is a lot of backward-compatibility to account for, even within File::Util itself.
In the last several years, there has never been a release of File::Util that intentionally broke code running a previous version. We are unaware of that even happening. File::Util is written to support both old and new features, syntaxes, and interfaces with full backward-compatibility.
๐ซถ Be helpful ๐ซถ
If requested, File::Util outputs extremely detailed error messages when something goes wrong in a File::Util operation. The diagnostic error messages not only provide information about what went wrong, but also hints on how to fix the problem.
These error messages can easily be turned on and off. See DIAGNOSTICS for the details.
๐ Be Pure ๐
File::Util uses no XS or C underpinnings that require you to have a compiler or make utility on your system in order to use it. Simply follow standard installation procedures (INSTALLATION) and you're done. No compiling required.
๐ What File::Util Is NOT ๐
File::Util offers significant performance increases over other modules for most directory-walking and searching, whether doing so in a single directory or in many directories recursively. (See also the benchmarking and profiling scripts included in the performance subdirectory as part of this distribution)*
However File::Util is NOT a single-purpose file-finding/searching utility like File::Find::Rule which offers a handful of extra built-in search features that File::Util does not give you out of the box, such as searching for files by owner/group or size. It is possible to accomplish the same things by taking advantage of File::Util's callbacks if you want to, but this isn't the "one thing" File::Util was built to do.
*Sometimes it doesn't matter how fast you can search through a directory 1000 times. Performance alone isn't the best criteria for choosing a module.
โญ SYNTAX โญ
In the past, File::Util relied on an older method invocation syntax that was not robust enough to support the newer features that have been added since version 4.0. In addition to making new features possible, the new syntax is more in keeping with what the Perl community has come to expect from its favorite modules, like Moose and DBIx::Class.
๐ OLD Syntax Example ๐
# this legacy syntax looks clunky and kind of smells like shell script
$f->list_dir( '/some/dir', '--recurse', '--as-ref', '--pattern=[^\d]' );
๐ฅ NEW Syntax Example (Does Much More) ๐ฅ
# This syntax is much more robust, and supports new features
$f->list_dir(
'/some/dir' => {
files_match => { or => [ qr/bender$/, qr/^flexo/ ] },
parent_matches => { and => [ qr/^Planet/, qr/Express$/ ] },
callback => \&deliver_interstellar_shipment,
files_only => 1,
recurse => 1,
as_ref => 1,
}
)
If you already have code that uses the old syntax, DON'T WORRY -- it's still fully supported behind the scenes. However, for new code that takes advantage of new features like higher order functions (callbacks), or advanced matching for directory listings, you'll need to use the syntax as set forth in this document. The old syntax isn't covered here, because you shouldn't use it anymore.
๐ An Explanation Of The "Options Hashref" ๐
As shown in the code example above, the new syntax uses hash references to specify options for calls to File::Util methods. This documentation refers to these as the "options hashref". The code examples below illustrates what they are and how they are used. Advanced Perl programmers will recognize these right away.
NOTE: "hashref" is short for "hash reference". Hash references use curly brackets and look like this:
my $hashref = { name => 'Larry', language => 'Perl', pet => 'Velociraptor' };
File::Util uses these hash references as argument modifiers that allow you to enable or disable certain features or behaviors, so you get the output you want, like this:
my $result = $ftl->some_method_call( arg1, arg2, { options hashref } );
# ^^^^^^^^^^^^^^^ #
A couple of real examples would look like this:
$ftl->write_file( '/some/file.txt', 'Hello World!', { mode => 'append' } );
# ^^^^^^^^^^^^^^^^ #
$ftl->list_dir( '/home/dangerian' => { recurse => 1, files_only => 1 } );
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #
๐ ERROR HANDLING ๐
โจ Feature Summary โจ
okay so bestie, managing errors is like a HUGE part of Perl IO, and File::Util has your back with a whole menu of options. literally every single call to a File::Util method that takes an "options hashref" can also carry an error handling directive with it. File::Util ships with some pre-defined error handling behaviors you can just pick off the shelf, or you can hand it your own custom error handler routine. all of this happens through the onfail option. ๐
and here's the โจconvenienceโจ part: when you use this option with the File::Util constructor method, it sets the default error handling policy for all failures. meaning โ set up one error handler for everything and then just... never think about it again. iconic behavior tbh. ๐
# Set every error to cause a warning instead of dying by default
my $ftl = File::Util->new( { onfail => 'warn' } );
$ftl->write_file( 'C:\\' => 'woof!' ); # now this call will warn and not die
๐ธ Details ๐ธ
the predefined onfail behaviors and their syntaxes are all covered below. no skipping, we go through every one ๐
- keyword:
diethis is what File::Util already does by default: it callsCORE::die()with an error message when it hits a fatal error, and your program just... ends. bye. ๐
Example:
my $ftl = File::Util->new( ... { onfail => 'die' } );
- keyword:
zerowhen you use the predefinedzerobehavior as youronfailhandler, File::Util will return a zero value (the integer 0) if it runs into a fatal error, instead of dying. it won't warn about the error, it won't abort execution. you just get a zero back instead of what you would've gotten otherwise, and execution keeps going like nothing ever happened. ๐ซถ
Example:
my $content = File::Util->load_file( ... { onfail => 'zero' } );
- keyword:
undefinedwhen you use the predefinedundefinedbehavior as youronfailhandler, if File::Util runs into a fatal error it will returnundef. execution will not be aborted, and no warnings will be issued. a value of undef just gets sent back to the caller instead of what you would've gotten otherwise. then execution continues on as if no error happened. ๐ฆ
Note: this option usually makes more practical sense than onfail => 'zero'
Example:
my $handle = File::Util->open_handle( ... { onfail => 'undefined' } );
- keyword:
warnwhen you use the predefinedwarnbehavior as youronfailhandler, File::Util will returnundefif it encounters a fatal error, instead of dying. then File::Util will emit a warning with details about the error, but it will not abort execution. you just get a warning message sent to STDERR andundefgets sent back to the caller instead of what you would've gotten otherwise. other than the warning, execution continues as if no error ever happened. ๐
Example:
my $write_ok = File::Util->write_file( ... { onfail => 'warn' } );
- keyword:
messagewhen you use the predefinedmessagebehavior as youronfailhandler, if File::Util runs into a fatal error it will return an error message in the form of a string containing details about the problem. execution will not be aborted, and no warnings will be issued. you just get an error message sent back to the caller instead of what you would've gotten otherwise. then execution continues on as if no error happened. ๐
Example:
my @files = File::Util->list_dir( ... { onfail => 'message' } );
subroutine referenceif you supply a code reference to theonfailoption in a File::Util method call, it will execute that code if it encounters a fatal error. you must supply a true code reference, like the ones in the examples below, either to a named or an anonymous subroutine. โจ
the subroutine you specify will receive two arguments as its input in @_. the first will be the text of the error message, and the second will be a stack trace in text format. you can send them to a logger, to your sysadmin in an email alert, or whatever you like โ because it is your error handler. ๐
โ ๏ธ WARNING! if you do not calldieorexitat the end of your error handler, File::Util will NOT exit, but continue to execute. when you opt to use this feature, you are fully responsible for your process' error handling and post-error execution. no takebacks, bestie ๐ญ
Examples using the constructor:
# step 1) define your custom error handler
sub politician_error_handler {
my ( $err, $stack ) = @_;
# do stuff like ...
$logger->debug( $stack );
die 'We neither confirm nor deny that an IO error has happened.';
}
# step 2) apply your error handler
my $ftl = File::Util->new( { onfail => \&politician_error_handler } );
-OR-
# Define and apply your error handler in one step:
my $ftl = File::Util->new(
{
onfail => sub {
my ( $err, $stack ) = @_;
# do stuff ...
}
}
);
Examples in individual method calls:
$ftl->write_file( 'greedo' => 'try bargain' => { onfail => \&shoot_first } );
my $file_handle = $ftl->open_handle(
'/this/might/not/work' => {
onfail => sub {
warn "Couldn't open first choice, trying a backup plan...";
return $ftl->open_handle( '/this/one/should/work' );
}
}
);
๐ DIAGNOSTICS ๐
when things go wrong, sometimes it's nice to get as much information as possible about the error. and in File::Util, you incur no performance penalties by enabling more verbose error messages. in fact, you're encouraged to do so. periodt. ๐
you can globally enable diagnostic messages (for every File::Util object you create), or on a per-object basis, or even on a per-call basis when you just want to diagnose a problem with a single method invocation. here's how, bestie: ๐
Enable Diagnostics Globally
use File::Util qw( :diag );
Enable Diagnostics Per-Object
my $ftl = File::Util->new( diag => 1 );
Enable Diagnostics Temporarily
$ftl->diagnostic( 1 ); # turn diagnostic mode on
# ... do some troubleshooting ...
$ftl->diagnostic( 0 ); # turn diagnostic mode off
Enable Diagnostics per-call
$ftl->load_file( 'abc.txt' => { diag => 1 } );
๐ METHODS ๐
Note: in the past, some of the methods listed would state that they were autoloaded methods. this mechanism has been changed in favor of more modern practices, in step with the evolution of computing over the last decade since File::Util was first released. glow up moment ๐
methods listed in alphabetical order.
๐ง atomize_path
Syntax: atomize_path( [/file/path or file_name] )
this method is used internally by File::Util to handle absolute filenames on different platforms in a portable manner, but it can be a useful tool for you as well. ๐ซถ
this method takes a single string as its argument. the string is expected to be a fully-qualified (absolute) or relative path to a file or directory. it carefully splits the string into three parts: the root of the path, the rest of the path, and the final file/directory named in the string.
depending on the input, the root and/or path may be empty strings. the following table can serve as a guide in what to expect from atomize_path():
+-------------------------+----------+--------------------+----------------+
| INPUT | ROOT | PATH-COMPONENT | FILE/DIR |
+-------------------------+----------+--------------------+----------------+
| C:\foo\bar\baz.txt | C:\ | foo\bar | baz.txt |
| /foo/bar/baz.txt | / | foo/bar | baz.txt |
| ./a/b/c/d/e/f/g.txt | | ./a/b/c/d/e/f | g.txt |
| :a:b:c:d:e:f:g.txt | : | a:b:c:d:e:f | g.txt |
| ../wibble/wombat.ini | | ../wibble | wombat.ini |
| ..\woot\noot.doc | | ..\woot | noot.doc |
| ../../zoot.conf | | ../.. | zoot.conf |
| /root | / | | root |
| /etc/sudoers | / | etc | sudoers |
| / | / | | |
| D:\ | D:\ | | |
| D:\autorun.inf | D:\ | | autorun.inf |
+-------------------------+----------+--------------------+----------------+
โญ bitmask
Syntax: bitmask( [file name] )
gets the bitmask of the named file, provided the file exists. if the file exists and is accessible, the bitmask of the named file is returned in four digit octal notation e.g.- 0644. otherwise, returns undef if the file does not exist or could not be accessed. ๐
๐ฅ can_flock
Syntax: can_flock
returns 1 if the current system claims to support flock() and if the Perl process can successfully call it. (see "flock" in perlfunc.) unless both of these conditions are true, a zero value (0) is returned. this is a constant method. it accepts no arguments and will always return the same value for the system on which it is executed. โจ
Note: Perl tries to support or emulate flock whenever it can via available system calls, namely flock; lockf; or with fcntl.
๐ created
Syntax: created( [file name] )
returns the time of creation for the named file in non-leap seconds since whatever your system considers to be the epoch. suitable for feeding to Perl's built-in functions gmtime and localtime. (see "time" in perlfunc.) โฐ
๐ diagnostic
Syntax: diagnostic( [true / false value] )
when called without any arguments, this method returns a true or false value to reflect the current setting for the use of diagnostic (verbose) error messages when a File::Util object encounters errors. ๐ง
when called with a true or false value as its single argument, this tells the File::Util object whether or not it should enable diagnostic error messages in the event of a failure. a true value indicates that the File::Util object will enable diagnostic mode, and a false value indicates that it will not. the default setting for diagnostic() is 0 (NOT enabled.)
see also DIAGNOSTICS
๐ธ "default_path" ๐ธ
Syntax: "default_path( [string, string] )"
the second string argument is optional, bestie ๐
It works just like strict_path, except that instead of handing you back undef when the thing you passed in doesn't look like a path, it returns a default string instead. That default string is either the built-in default path, or whatever string you gave it as the second argument to this method. Your choice ๐ซถ
The default string it returns is '.' . SL (go peek at SL for that one).
Which means on windows the built-in default is ".\", whereas on a POSIX-compliant system (Linux, UNIX, Mac, etc) you'd get "./" โจ
see also strict_path ๐
๐ "ebcdic" ๐
Syntax: "ebcdic"
Returns 1 if the machine the code is running on uses EBCDIC, or returns 0 if not (see perlebcdic). This is a constant method โ it takes no arguments and will always return the same value for the system it's executed on. Iconic, honestly, no notes ๐
๐ "escape_filename" ๐
Syntax: "escape_filename( [string], [escape char] )"
Gives you back its argument in an escaped form that's suitable for use as a filename. Illegal characters โ that's any type of newline character, tab, vtab, and the following / | * " ? < : > \ โ get replaced with [escape char], or with "_" if you didn't specify an [escape char]. And if you hand it no arguments at all, you get an empty string back. slay ๐
๐ฆ "existent" ๐ฆ
Syntax: "existent( [file name] )"
Returns 1 if the named file (or directory) exists. Otherwise you get a value of undef.
This does the exact same thing as Perl's built-in -e file test operator (see "-X" in perlfunc) โ it's just easier for some people to remember, iykyk ๐
๐ "file_type" ๐
Syntax: "file_type( [file name] )"
Returns a list of keywords matching each of Perl's built-in file tests (the ones specific to file types) that come back true for the named file (see "-X" in perlfunc).
Here are the keywords and their definitions, and the order they get returned in is the same order they're listed in right here โฌ๏ธ
"PLAIN File is a plain file."
"TEXT File is a text file."
"BINARY File is a binary file."
"DIRECTORY File is a directory."
"SYMLINK File is a symbolic link."
"PIPE File is a named pipe (FIFO)."
"SOCKET File is a socket."
"BLOCK File is a block special file."
"CHARACTER File is a character special file."
๐
"flock_rules" ๐
Syntax: "flock_rules( [keyword list] )"
This one sets your I/O race condition policy โ basically it tells File::Util how it should handle race conditions that show up when a file can't be locked because it's already locked somewhere else (usually by another process). the drama ๐ญ
Call it with nothing and you get back a list of keywords representing the rules currently in effect for the object.
Otherwise, your call should include a list of your chosen directive keywords in order of precedence. The rules get applied in cascading order whenever a File::Util object tries to lock a file โ so if the actions from the first rule don't succeed, the second rule kicks in, and so on down the line. cascade, bestie ๐
You can change this setting dynamically at literally any point in your code by calling this method whenever you want.
The default behavior of File::Util is to try and get an exclusive lock on all file opens (if your operating system supports it). If a lock can't be obtained, File::Util will throw an exception and exit. periodt ๐
If you want different behavior, this method is how you get it. One super common situation is wanting your code to first try for a lock, and failing that, wait until one can be obtained. If that's your vibe, check the examples after the keywords list below ๐
Recognized keywords:
"NOBLOCKEX"โ tries to get an exclusive lock on the file without blocking (waiting)"NOBLOCKSH"โ tries to get a shared lock on the file without blocking"BLOCKEX"โ waits to get an exclusive lock"BLOCKSH"โ waits to get a shared lock"FAIL"โ dies with stack trace"WARN"โwarn()s about the error and returnsundef"IGNORE"โ ignores the failure to get an exclusive lock"UNDEF"โ returnsundef"ZERO"โ returns0
Examples:
ex- "flock_rules( qw( NOBLOCKEX FAIL ) );"
This is the default policy. When it's in effect, the File::Util object will first attempt to get a non-blocking exclusive lock on the file. If that attempt fails, the File::Util object will call die() with an error. that's the default, don't come for me ๐
ex- "flock_rules( qw( NOBLOCKEX BLOCKEX FAIL ) );"
The File::Util object will first attempt to get a non-blocking exclusive lock on the file. If that attempt fails, it falls back to the second policy rule "BLOCKEX" and tries again to get an exclusive lock on the file โ but this time by blocking (waiting for its turn). If that second attempt fails, the File::Util object will fail with an error.
ex- "flock_rules( qw( BLOCKEX IGNORE ) );"
The File::Util object will first attempt to get a file non-blocking lock on the file. If that attempt fails, it will ignore the error and go on to open the file anyway, and no failures or warnings will occur. we love a chill policy ๐
โญ "is_bin" โญ
Syntax: "is_bin( [file name] )"
Returns 1 if the named file (or directory) exists. Otherwise you get a value of undef, which means the named file either doesn't exist or is some other file type entirely.
This works the same as Perl's built-in -B file test operator (see "-X" in perlfunc) โ it's just easier for some people to remember ๐
๐ง "is_readable" ๐ง
Syntax: "is_readable( [file name] )"
Returns 1 if the named file (or directory) is readable by your program, according to the applied permissions of the file system the file lives on. Otherwise you get a value of undef.
This works the same as Perl's built-in -r file test operator (see "-X" in perlfunc) โ it's just easier for some people to remember โจ
๐ซถ "is_writable" ๐ซถ
Syntax: "is_writable( [file name] )"
Returns 1 if the named file (or directory) is writable by your program, according to the applied permissions of the file system the file lives on. Otherwise you get a value of undef.
This works the same as Perl's built-in -w file test operator (see "-X" in perlfunc) โ it's just easier for some people to remember ๐ธ
๐ "last_access" ๐
Syntax: "last_access( [file name] )"
Returns the last accessed time for the named file, in non-leap seconds since whatever your system considers to be the epoch. Perfectly suited for feeding to Perl's built-in functions "gmtime" and "localtime" (see "time" in perlfunc).
๐ "last_changed" ๐
Syntax: "last_changed( [file name] )"
Returns the inode change time for the named file, in non-leap seconds since whatever your system considers to be the epoch. Perfectly suited for feeding to Perl's built-in functions "gmtime" and "localtime" (see "time" in perlfunc).
๐ฅ "last_modified" ๐ฅ
Syntax: "last_modified( [file name] )"
Returns the last modified time for the named file, in non-leap seconds since whatever your system considers to be the epoch. Perfectly suited for feeding to Perl's built-in functions "gmtime" and "localtime" (see "time" in perlfunc).
๐ "line_count" ๐
Syntax: "line_count( [file name] )"
Returns the number of lines in the named file. It fails with an error if the named file doesn't exist. no file, no count, sorry bestie ๐ญ
โจ "list_dir" โจ
Syntax: "list_dir( [directory name] => { option => value, ... } )"
Returns all file names in the specified directory, sorted in alphabetical order. It fails with an error if no such directory is found, or if the directory is inaccessible.
okay so, note that this is one of File::Util's most robust methods and it can be very useful. It can be used as a higher order function (it accepts callback subrefs!), and it can be used for advanced pattern matching against files. It can also return a hierarchical data structure of the file tree you ask it to walk. she does it all ๐
See the File::Util::Manual::Examples for several useful ways to use "list_dir()".
Syntax example to recursively return a list of subdirectories in directory dir_name:
my @dirs = $f->list_dir( 'dir_name' => { dirs_only => 1, recurse => 1 } );
Options accepted by "list_dir()"
"callback => subroutine reference"
"list_dir()" can accept references to subroutines of your own. If you pass it a code reference using this option, File::Util will execute your code every single time list_dir() enters a directory. This is particularly useful when combined with the "recurse" option, which is explained below.
When you create a callback function, File::Util will pass it four arguments, in this order: the name of the current directory, a reference to a list of subdirectories in the current directory, a reference to a list of files in the current directory, and the depth (a positive integer) relative to the directory you provided as your first argument to "list_dir()". So if you pass in a path such as /var/tmp, then /var/tmp is at a depth of 0, /var/tmp/foo is 1 deep, and so on down through the /var/tmp directory.
Remember that the code in your callback gets executed in real time, as list_dir() is walking the directory tree. Consider this example:
# Define a subroutine to print the byte size and depth of all files in a
# directory, designed to be used as a callback function to list_dir()
sub filesize {
my ( $selfdir, $subdirs, $files, $depth ) = @_;
print "$_ | " . ( -s $_ ) . " | $depth levels deep\n" for @$files;
}
# Now list directory recursively, invoking the callback on every recursion
$f->list_dir( './droids' => { recurse => 1, callback => \&filesize } );
Another way to use callbacks is in combination with closures, to "close around" a variable or variables defined in the same scope as the callback. A demonstration of this technique is shown below:
{
my $size_total;
my $dir = 'C:\Users\superman\projects\scripts_and_binaries';
# how many total bytes are in all of the executable files in $dir
$f->list_dir(
$dir => {
callback => sub {
my ( $selfdir, $subdirs, $files, $depth ) = @_;
$size_total += -s $_ for grep { -B $_ } @$files;
}
}
);
print "There's $size_total bytes of binary files in my projects dir.";
}
d_callback => subroutine reference
A d_callback is just like a callback, except it only fires on directories you bump into in the file tree โ never on files โ and its input is a lil different. @_ is made up of (in order) the name of the current directory, a reference to a list of all subdirectories in that directory, and the depth (a positive integer) relative to the top level directory in the path you handed over as your first argument to list_dir. ๐ซถ
f_callback => subroutine reference
Same energy: an f_callback is just like a callback, except it's only concerned with files encountered in the file tree, not directories. Its input is also slightly different. @_ is comprised of (in order) the name of the current directory, a reference to a list of all files present in that directory, and the depth (positive integer) relative to the top level directory in the path you provided as your first argument to list_dir. โจ
dirs_only => boolean
return only directory contents which are also directories ๐
files_only => boolean
return only directory contents which are files ๐
max_depth => positive integer
Works just like the -maxdepth flag in the GNU find command. This option tells list_dir() to limit results to directories at no more than the maximum depth you specify. This only works in tandem with the recurse option (or the recurse_fast option which is similar). ๐ฅ
For compatibility reasons, you can use "maxdepth" without the underscore instead, and get the same functionality. (yes bestie, both spellings eat. no cap.)
no_fsdots => boolean
do not include . and .. in the list of directory contents returned ๐
abort_depth => positive integer
Override the global limit on abort_depth recursions for directory listings, on a per-listing basis with this option. Just like the main abort_depth() object method, this option takes a positive integer. The default is 1000. Sometimes it is useful to increase this number by quite a lot when walking directories with callbacks. ๐ง
with_paths => boolean
Return results with the preceding file paths intact, relative to the directory named in the call. ๐ธ
recurse => boolean
Recurse into subdirectories. In other words, open up subdirectories and continue to descend into the directory tree either as far as it goes, or until the abort_depth limit is reached. See abort_depth() ๐ฆ
recurse_fast => boolean
Recurse into subdirectories, without checking for filesystem loops. This works exactly like the recurse option, except it turns off internal checking for duplicate inodes while descending through a file tree.
You get a performance boost at the sacrifice of a little "safety checking". ๐
The bigger your file tree, the more performance gains you see. ๐
This option has no effect on Windows. (see perldoc -f stat)
dirs_as_ref => boolean
When returning directory listing, include first a reference to the list of subdirectories found, followed by anything else returned by the call. ๐
files_as_ref => boolean
When returning directory listing, include last a reference to the list of files found, preceded by a list of subdirectories found (or preceded by a list reference to subdirectories found if dirs_as_ref was also used). ๐
as_ref => boolean
Return a pair list references: the first is a reference to any subdirectories found by the call, the second is a reference to any files found by the call. ๐ซถ
sl_after_dirs => boolean
Append a directory separator (/, \, or : depending on your system) to all directories found by the call. Useful in visual displays for quick differentiation between subdirectories and files. โญ
ignore_case => boolean
Return items in a case-insensitive alphabetic sort order, as opposed to the default.
**By default, items returned by the call to this method are alphabetically sorted in a case-insensitive manner, such that "Zoo.txt" comes before "alligator.txt". This is also the way files are listed at the system level on most operating systems.
However, if you'd like the directory contents returned by this method to be sorted without regard to case, use this option. That way, "alligator.txt" will come before "Zoo.txt". ๐ญ
count_only => boolean
Returns a single value: an integer reflecting the number of items found in the directory after applying any filter criteria that may also have been specified by other options (i.e.- dirs_only, recurse, etc.) ๐ข
as_tree => boolean
Returns a hierarchical data structure (hashref) of the file tree in the directory you specify as the first argument to list_dir(). Use in combination with other options to get the exact results you want in the data structure. ๐ณ
*Note: When using this option, thefiles_onlyanddirs_onlyoptions are ignored, but you can still specify things like amax_depthargument, however. Note also that you need to specifically call this with therecurseorrecurse_fastoption or you will only get a single-level tree structure.
One quick example:
my $tree = $ftl->list_dir(
'/tmp' => {
as_tree => 1,
recurse => 1,
}
);
# output would look something like this if you Data::Dumper'd it
{
'/' => {
'_DIR_PARENT_' => undef,
'_DIR_SELF_' => '/',
'tmp' => {
'_DIR_PARENT_' => '/',
'_DIR_SELF_' => '/tmp',
'hJMOsoGuEb' => {
'_DIR_PARENT_' => '/tmp',
'_DIR_SELF_' => '/tmp/hJMOsoGuEb',
'a.txt' => '/tmp/hJMOsoGuEb/a.txt',
'b.log' => '/tmp/hJMOsoGuEb/b.log',
'c.ini' => '/tmp/hJMOsoGuEb/c.ini',
'd.bat' => '/tmp/hJMOsoGuEb/d.bat',
'e.sh' => '/tmp/hJMOsoGuEb/e.sh',
'f.conf' => '/tmp/hJMOsoGuEb/f.conf',
'g.bin' => '/tmp/hJMOsoGuEb/g.bin',
'h.rc' => '/tmp/hJMOsoGuEb/h.rc',
}
}
}
}
When using this option, the hashref you get back will have certain metadata entries at each level of the hierarchy, namely there will be two special keys: _DIR_SELF, and _DIR_PARENT_. Their values will be the name of the directory itself, and the name of its parent, respectively. ๐
That metadata can be extremely helpful when iterating over and parsing the hashref later on, but if you don't want the metadata, include the dirmeta option and set it to a zero (false) value as shown below:
my $tree = $ftl->list_dir(
'/some/dir' => {
as_tree => 1,
recurse => 1,
dirmeta => 0,
}
);
**Remember: the as_tree doesn't recurse into subdirectories unless you tell it to with recurse => 1 ๐ค
๐ธ Filtering and Matching with list_dir() ๐ธ
okay bestie this is the glow-up part of list_dir(). it can take Perl Regular Expressions and match them against stuff, which is how you filter what comes back at you. it can match on file name, directory name, the path preceding results, and the parent directory of results. and listen โ the matching arguments you hand it must be real regular expression references, like actually qr// objects. NOT strings. do not pass a string. she will not know what to do with it. ๐
regexes can come in as a single argument value, OR as a specifically crafted hashref that designates a list of patterns to match against โ either in an "or" manner, or in an "and"'ed cumulative manner.
some short examples of proper syntax will show up right after the list of matching options below. โจ
โ ๏ธ real talk: if you experience a big slowdown in directory listings while using regular expressions, check that your regexes are properly written and optimized. in general, directory listings should not be slow or resource-intensive. badly-written regular expressions will result in considerable slowdowns and bottlenecks in any application. no cap, this is a you problem not a Perl problem. ๐ซถ
files_match => qr/regexp/ORfiles_match => { and/or => [ qr/listref of/, qr/regexps/ ] }โ returns only file names matching the regex(es). ๐ preceding directories are included in the results; for technical reasons they are not excluded (if they were excluded,list_dir()wouldn't be able to "cascade" or recurse into subdirectories in search of matching files). pro tip: pair this with thefiles_onlyoption to actually kick those preceding directory names out of your results.dirs_match => qr/regexp/ORdirs_match => { and/or => [ qr/listref of/, qr/regexps/ ] }โ returns only files and subdirectory names that live in directories matching the regex(es) you specify. BE CAREFUL with this one!! it doesn't "cascade" the way you might expect; for technical reasons, it won't descend into directories that don't match the regex(es) you provide. so like, if you wanna match a directory name that's three levels deep against a given pattern, but you don't know (or don't care about) the names of the intermediate directories โ THIS IS NOT THE OPTION YOU ARE LOOKING FOR. use thepath_matchesoption instead. ๐
*NOTE: bear in mind that just because you telllist_dir()to match each directory against the regex(es) you specify here, that does <u>not</u> mean you're telling it to only show directories in its results. you will get file names in matching directories included in the results as well, unless you combine this with thedirs_onlyoption. iykyk.
path_matches => qr/regexp/ORpath_matches => { and/or => [ qr/listref of/, qr/regexps/ ] }โ returns only files and subdirectory names whose preceding paths match the regex(es) you specify. ๐ฆparent_matches => qr/regexp reference/ORparent_matches => { and/or => [ qr/listref of/, qr/regexps/ ] }โ returns only files and subdirectory names whose parent directory matches the regex(es) you specify. ๐
Examples of matching and filtering results in listdir() โจ
Single-argument matching examples โ one regex, one vibe, so clean:
my @files = $f->list_dir(
'../notes' => { files_match => qr/\.txt$/i, files_only => 1 }
);
my @dirs = $f->list_dir(
'/var' => {
dirs_match => qr/log|spool/i,
recurse => 1,
dirs_only => 1,
}
);
my @dirs = $f->list_dir(
'/home' => {
path_matches => qr/Desktop/,
recurse => 1,
dirs_only => 1,
}
);
my @files = $f->list_dir(
'/home/tommy/projects' => {
parent_matches => qr/^\.git$/,
recurse => 1,
}
);
A multiple-argument matching examples with OR โ match this OR that, she's flexible like that:
my @files = $f->list_dir(
'C:\Users\Billy G' => {
parent_matches => { or => [ qr/Desktop/, qr/Pictures/ ] }
recurse => 1,
}
);
# ... same concepts apply to "files_match", "dirs_match",
# and "parent_matches" filtering
Multiple-argument matching examples with AND โ everything's gotta hit, no skipping:
my @files = $f->list_dir(
'/home/leia' => {
parent_matches => { and => [ qr/Anakin/, qr/Amidala/ ] }
recurse => 1,
}
);
my @files = $f->list_dir(
'/home/mace' => {
path_matches => { and => [ qr/^(?!.*dark.side)/i, qr/[Ff]orce/ ] }
recurse => 1,
}
);
# ... same concepts apply to "files_match" and "dirs_match" filtering
โ ๏ธ when you specify regexes for more than one filter type parameter, the patterns are AND'ed together, as you'd expect, and all matching criteria must be satisfied for a successful overall match. no partial credit bestie. ๐
my @files = $f->list_dir(
'/var' => {
dirs_match => { or => [ qr/^log$/, qr/^lib$/ ] },
files_match => { or => [ qr/^syslog/, qr/\.isam$/i ] },
parent_matches => qr/[[:alpha:]]+/
path_matches => qr/^(?!.*home)/,
recurse => 1,
files_only => 1,
}
Negative matches (when you want to NOT match something) - use Perl! ๐ง
as shown in the File::Util::Manual::Examples, Perl already provides support for negated matching in the form of "zero-width negative assertions". (see perlre for details on how they work). use syntax like the regular expressions below to match anything that is NOT part of the subpattern.
# match all files with names that do NOT contain "apple" (case sensitive)
my @no_apples = $f->list_dir(
'Pictures/fruit' => { files_match => qr/^(?!.*apple)/ }
);
# match all files that that do NOT end in *.mp3 (case INsensitive)
# also, don't match files that end in *.wav either
my @no_music = $f->list_dir(
'/opt/music' => {
files_match => { and => [ qr/^(?!.*mp3$)/i, qr/^(?!.*wav$)/i ]
}
);
๐ load_dir ๐
Syntax: load_dir( [directory name] => { options } )
returns a data structure containing the contents of each file present in the named directory. ๐โจ
the type of data structure returned is determined by the optional data-type option parameter. only one option at a time may be used for a given call to this method. recognized options are listed below.
my $files_hash_ref = $f->load_dir( $dirname ); # default (hashref)
-OR-
my $files_list_ref = $f->load_dir( $dirname => { as_listref => 1 } );
-OR-
my @files = $f->load_dir( $dirname => { as_list => 1 } );
Options accepted by load_dir()
as_hashref => boolean(default) โ implicit, bestie. if no option is passed in, the default behavior is to return a reference to an anonymous hash whose keys are the names of each file in the specified directory; the hash values for contain the contents of the file represented by its corresponding key. ๐as_list => booleanโ causes the method to return a list comprised of the contents loaded from each file (in case-sensitive order) located in the named directory.
this is useful in situations where you don't care what the filenames were and you just want a list of file contents. main character energy: the content matters, not the name. ๐
as_listref => booleanโ same as above, except an array reference to the list of items is returned rather than the list itself. this is more efficient than the above, particularly when dealing with large lists. ๐ฅ
load_dir() does not recurse or accept matching parameters, etc. it's an effective tool for loading up things like a directory of template files on a web server, or to store binary data streams in memory. use it however you like. ๐
however, if you <i>do</i> want to load files into a hashref/listref or array while using the advanced features of list_dir(), just use list_dir to return the files and map the contents into your variable:
my $hash_ref = {};
%$hash_ref = map { $_ => $ftl->load_file( $_ ) }
$ftl->list_dir( $dir_name => { advanced options... } );
Note: this method does not distinguish between plain files and other file types such as binaries, FIFOs, sockets, etc. ๐
restrictions imposed by the current "read limit" (see the read_limit() entry below) will be applied to the individual files opened by this method as well. adjust the read limit as necessary. โ ๏ธ
example usage:
my $templates = $f->load_dir( 'templates/stock-ticker' );
the above code creates an anonymous hash reference that is stored in the variable named $files. the keys and values of the hash referenced by $files would resemble those of the following code snippet (given that the files in the named directory were the files 'a.txt', 'b.html', 'c.dat', and 'd.conf')
my $files =
{
'a.txt' => 'the contents of file a.txt',
'b.html' => 'the contents of file b.html',
'c.dat' => 'the contents of file c.dat',
'd.conf' => 'the contents of file d.conf',
};
๐ธ load_file ๐ธ
Syntax: load_file( [file name] => { options } )
OR: load_file( file_handle => [file handle reference] => { options } )
if <i>[file name]</i> is passed, returns the contents of <i>[file name]</i> in a string. if a <i>[file handle reference]</i> is passed instead, the filehandle will be CORE::read() and the data obtained by the read will be returned in a string. ๐
okay so if you want the file contents (or filehandle data) as a list of lines instead of one big string, that's literally what the as_lines option is for (more on that below ๐
).
Options accepted by load_file()
as_lines => booleanโ turn this on and yourload_filecall hands you back a list of strings, and each string is one line exactly as it got read from the file [file name]. The lines come back in the order they were read, top of the file to the bottom. This is not the default, bestie. The default is one single string holding the entire contents of the file. ๐no_lock => booleanโ by default this method tries to grab a lock on the file while it's being read, following whatever rules are in place for the flock policy that got established either by default (implicitly) or that you changed in a call toFile::Util::flock_rules()(peep theflock_rules()entry below ๐).
This method will not try to get a lock on the file if the File::Util object was created with the option no_lock, or if the method itself was called with the option no_lock.
This method automatically calls binmode() on binary files for you ๐ซถ. But if you pass in a filehandle instead of a file name, you do not get this automatic check. In that case you'll have to call binmode() on the filehandle yourself. Once you pass a filehandle to this method, it has no way of telling if the file opened to that filehandle is binary or not. ๐
binmode => [ boolean or 'utf8' ]โ tell File::Util to read the file in binmode (if you set it to a true boolean:1), or to read the file as UTF-8 encoded data by specifying a value ofutf8to this option. (see"binmode"in perlfunc).
You need Perl 5.8 or better to use 'utf8' or your program will fail with an error message. ๐จ
Example Usage:
my $encoded_data = $ftl->load_file( 'encoded.txt' => { binmode => 'utf8' } );
read_limit => positive integerโ override the global read limit setting for the File::Util object you're working with, on a one-time basis โจ. Specify this option with a positive integer value (that's the max number of bytes to allow for yourload_file()call) and you're tellingload_file()to ignore the global/default setting for just that call, and apply your one-time limit of [positive integer] bytes on the file while it's read into memory.
Notes: this method does not distinguish between plain files and other file types such as binaries, FIFOs, sockets, etc. ๐
Restrictions imposed by the current "read limit" (see the read_limit() entry below) will be applied to the files opened by this method. Adjust the read limit as necessary, either by overriding it (using the 'read_limit' option above) or by adjusting the global value for your File::Util object with the provided read_limit() object method. ๐ช
make_dir
Syntax: make_dir( [new directory name], [bitmask] => { options } )
Attempts to create (recursively) a directory as [new directory name] with the [bitmask] provided. The bitmask is an optional argument and defaults to oct 777, combined with the current user's umask. If specified, the bitmask must be supplied in the form required by the native perl umask function (as an octal number). see "umask" in perlfunc for more info about the format of the bitmask argument. ๐ง
As mentioned above, the recursive creation of directories is transparently handled for you. Which means: if the name of the directory you pass in contains a parent directory that does not exist, the parent directory(ies) will be created for you automatically and silently, in order to create the final directory in the [new directory name]. ๐ช
Simply put, if [new directory] is "/path/to/directory" and the directory "/path/to" does not exist, then "/path/to" will be created, and the "/path/to/directory" directory will be created thereafter. All directories created will be created with the [bitmask] you specify, or with the default of oct 777, combined with the current user's umask.
Upon successful creation of the [new directory name], the [new directory name] is returned to the caller. ๐
Options accepted by make_dir()
if_not_exists => booleanโ Example:
$f->make_dir( '/home/jspice' => oct 755 => { if_not_exists => 1 } );
Turn this option on and make_dir will not attempt to create the directory if it already exists. Instead it just returns the name of the directory, exactly like it normally would if the directory hadn't existed before you called this method. ๐ฆ
If you call this method without the if_not_exists option and the directory specified as [new directory name] does in fact exist, an error will result, because it is impossible to create a directory that already exists. periodt. ๐
abort_depth
Syntax: abort_depth( [positive integer] )
Call it with no arguments and this method returns an integer reflecting the current number of times the File::Util object will dive into the subdirectories it discovers when recursively listing directory contents from a call to File::Util::list_dir(). The default is 1000. If that number gets exceeded, the File::Util object will fail with an error. ๐ญ
Call it with an argument and it sets the maximum number of times a File::Util object will recurse into subdirectories before failing with an error message.
This method can only be called with a numeric integer value. Passing a bad argument to this method will cause it to fail with an error. no cap.
(see also: list_dir)
needs_binmode
Syntax: needs_binmode
Returns 1 if the machine the code is running on requires that binmode() (a built-in function) be called on open file handles, or returns 0 if not. (see "binmode" in perlfunc.) This is a constant method. It accepts no arguments and will always return the same value for the system it's executed on. ๐ฅ
new
Syntax: new( { options } )
This is the File::Util constructor method, the main character of the whole operation ๐. It returns a new File::Util object reference when you call it. It recognizes various options that govern the behavior of the new File::Util object.
Parameters accepted by new()
use_flock => booleanโ optionally specify this option to theFile::Util::newmethod to instruct the new object that it should never attempt to useflock()in its I/O operations. The default is to useflock()if it's available on your system. Specify this option with a true or false value (1or0): true to useflock(), false to not use it. ๐read_limit => positive integerโ optionally specify this option to the File::Util::new method to instruct the new object that it should never attempt to open and read in a file greater than the number of bytes you specify. This argument can only be a numeric integer value, otherwise it will be silently ignored. The default read limit for File::Util objects is 52428800 bytes (50 megabytes). ๐ฎabort_depth => positive integerโ optionally specify this option to the File::Util::new method to instruct the new object to set the maximum number of times it will recurse into subdirectories while performing directory listing operations before failing with an error message. This argument can only be a numeric integer value, otherwise it will be silently ignored.
(see also: abort_depth())
onfail => designated handlerโ set the default policy for how the new File::Util object handles fatal errors. This option takes any one of a list of predefined keywords, or a reference to a named or anonymous error handling subroutine of your own. ๐ซถ
You can supply an onfail handler to nearly any function in File::Util, but when you do it for the new() constructor, you're setting the default.
Acceptable values are all covered in the ERROR HANDLING section (above), along with proper syntax and example usage.
onfail
Syntax: onfail( [keyword or code reference] )
Dynamically set/change the default error handling policy for an object. โจ
This works exactly the same as when you specify an onfail handler to the constructor method (see also new).
The syntax and keywords available for this method are already discussed above in the ERROR HANDLING section, so go peep that for the in-depth details. ๐
Here are some examples:
$ftl->onfail( 'die' );
$ftl->onfail( 'zero' );
$ftl->onfail( 'undefined' );
$ftl->onfail( 'message' );
$ftl->onfail( \&subroutine_reference );
$ftl->onfail( sub { my ( $error, $stack_trace ) = @_; ... } );
open_handle
Syntax: open_handle( [file name] => [mode] => { options } )
OR: open_handle( file => [file name] => mode => [mode] => { options } )
Attempts to get a lexically scoped open file handle on [file name] in [mode] mode. Returns the file handle if successful, or generates a fatal error with a diagnostic message if the operation fails. ๐
You will need to remember to callclose()on the filehandle yourself, at your own discretion. Leaving filehandles open is not good practice and is not recommended. (see"close"in perlfunc). ๐
So like, once you've got that file handle in your cute lil hands, you just use it like any other file handle. Easy. But remember โ unless you specifically turned file locking <span>off</span> when the File::Util object was made (peep new) or you passed the no_lock option when you called open_handle, then that file locking is gonna automagically get handled for you behind the scenes, as long as your OS supports file locking of any kind at all. Slay! It's genuinely so convenient that you don't have to worry about portability when you're taking care of file locking from one app to the next; by using File::Util in all of them, you know you're covered. ๐
A slight inconvenience, for the price of a bigger feature set (go compare write_file to this method, fr), is that you have to release the file lock on the open handle yourself. File::Util can't manage it for you anymore once it hands the handle over to you. At that point? It's all yours, bestie. ๐ญ To release the file lock on your file handle, call unlock_open_handle() on it. Otherwise that lock will just remain for the life of your process. If you don't want to use the free portable file locking, remember the no_lock option, which turns file locking off for your open handle. But ngl, you should seldom ever opt to not use file locking unless you really, truly know what you're doing. The only obvious exception is if you're working with files on a network-mounted filesystem like NFS or SMB (CIFS), in which case locking can be buggy. ๐
If the file doesn't exist yet, it will be created, and it'll be created with a bitmask of [bitmask] if you specify a file creation bitmask using the 'bitmask' option. Otherwise, the file gets created with the default bitmask of oct 777. The bitmask is combined with the current user's umask, whether you specify a value or not. That's a function of Perl, not File::Util, iykyk.
If specified, the bitmask must be supplied in the form of an octal number, as required by the native perl umask function. See "umask" in perlfunc for more on the format of the bitmask argument. If the file [file name] already exists, then the bitmask argument has no effect and is silently ignored. ๐
Any non-existent directories in the path preceding the actual file name will be automatically (and silently โ no warnings) created for you, and any new directories will be created with a bitmask of [dbitmask], provided you specify a directory creation bitmask with the 'dbitmask' option. โจ
If specified, the directory creation bitmask [dbitmask] must be supplied in the form required by the native perl umask function.
If there's an error while trying to create any preceding directories, that failure results in a fatal error with an error. And if all the directories preceding the name of the file already exist, the dbitmask argument has no effect and is silently ignored. Periodt.
๐ Native Perl open modes ๐
The default behavior of open_handle() is to open file handles using Perl's native open() (see "open" in perlfunc). Unless you use the use_sysopen option, only then are the following modes valid:
"mode => 'read'"โ this is the default mode. [file name] is opened in read-only mode. If the file doesn't exist yet, then a fatal error will occur."mode => 'write'"โ [file name] is created if it doesn't exist yet. If [file name] already exists, then its contents are overwritten with the new content you provide."mode => 'append'"โ [file name] is created if it doesn't exist yet. If [file name] already exists, its contents will be preserved and the new content you provide will be appended to the end of the file.
๐ฅ System level open modes ("open a la C") ๐ฅ
Optionally you can ask File::Util to open your handle using CORE::sysopen instead of using the native Perl CORE::open(). You do this by enabling the use_sysopen option. Using this feature opens up more possibilities as far as the open modes you can pick from, but it also carries a few caveats, so you gotta be careful โ just like you'd have to be a little more careful when using sysopen() anyway.
Specifically, you need to remember that when you use this feature, you must NOT mix different types of I/O when working with the file handle. You can't go opening file handles with sysopen() and then print to them like you'd normally print to a file handle. You have to use syswrite() instead. Same applies here. If you get a sysopen()'d filehandle from open_handle(), it is imperative that you use syswrite() on it. You'll also need to use sysseek() and other "sys"* commands on the filehandle instead of their native Perl equivalents.
(see "sysopen" in perlfunc, "syswrite" in perlfunc, "sysseek" in perlfunc, "sysread" in perlfunc)
That said, here are the different modes you can choose from to get a file handle when you're using the use_sysopen option. Remember: these won't work unless you use that option, and they'll generate an error if you try using them without it. The standard 'read', 'write', and 'append' modes are already available to you by default. These are the extended modes:
"mode => 'rwcreate'"โ [file name] is opened in read-write mode, and will be created for you if it doesn't already exist."mode => 'rwupdate'"โ [file name] is opened for you in read-write mode, but it must already exist. If it doesn't exist, a fatal error will result."mode => 'rwclobber'"โ [file name] is opened for you in read-write mode. If the file already exists, its contents will be "clobbered" or wiped out. The file will then be empty and you'll be working with the then-truncated file. This can not be undone. Once you callopen_handle()using this option, your file WILL be wiped out. If the file doesn't exist yet, it'll be created for you. ๐ญ"mode => 'rwappend'"โ [file name] will be opened for you in read-write mode, ready for appending. The file's contents will not be wiped out; they'll be preserved and you'll be working in append fashion. If the file doesn't exist, it'll be created for you.
Remember to use sysread() and not plain read() when reading those sysopen()'d filehandles!
๐ Options accepted by open_handle() ๐
"binmode => [ boolean or 'utf8' ]"โ tell File::Util to open the file inbinmode(if set to a true boolean: 1), or to open the file with UTF-8 encoding, specify a value of"utf8"to this option. (see"binmode" in perlfunc).
You need Perl 5.8 or better to use "utf8" or your program will fail with an error message.
Example Usage:
$ftl->open_handle( 'encoded.txt' => { binmode => 'utf8' } );
"no_lock => boolean"โ by default this method will attempt to get a lock on the file while it's being read, following whatever rules are in place for the flock policy established either by default (implicitly) or changed by you in a call toFile::Util::flock_rules()(seeflock_rules()).
This method will not try to get a lock on the file if the File::Util object was created with the option no_lock, or if this method is called with the option no_lock.
"use_sysopen => boolean"โ instead of opening the file using Perl's nativeopen()command,File::Utilwill open the file with thesysopen()command. You'll have to remember that your filehandle is asysopen()'d one, and that you won't be able to use native Perl I/O functions on it. You'll have to use the"sys"*equivalents. Seeperlopentutfor a more in-depth explanation of why you can't mix native Perl I/O with system I/O.
๐ธ "read_limit" ๐ธ
Syntax: "read_limit( [positive integer] )"
By default, the largest size file that File::Util will read into memory and return via the load_file is 52428800 bytes (50 megabytes). ๐
This value can be modified by calling this method with an integer value reflecting the new limit you want to impose, in bytes. So for example, if you want to set the limit to 10 megabytes, call the method with an argument of 10485760.
If this method is called without an argument, the read limit currently in force for the File::Util object will be returned.
๐ฆ "return_path" ๐ฆ
Syntax: "return_path( [string] )"
Takes the file path from the file name provided and returns it such that "/who/you/callin/scruffy.txt" is returned as "/who/you/callin".
This method is optimized for speed and returns anything that could possibly be a file path โ even if that means the path is actually "foo.bar" if you passed it such an argument. Technically, you could indeed have a directory named "blaster.txt", so this method doesn't distinguish between strings that look like file names and ones that don't. ๐
If you want one that does, you need to use "strict_path()" instead. (see strict_path)
โญ "size" โญ
Syntax: "size( [file name] )"
Returns the file size of [file name] in bytes. Returns 0 if the file is empty. Returns "undef" if the file does not exist.
๐ง "split_path" ๐ง
Syntax: "split_path( [string] )"
Takes a path/filename, fully-qualified or relative (it literally doesn't matter which), and it returns a list comprising the root of the path (if any), each directory in the path, and the final part of the path (be it a file, a directory, or otherwise).
This method doesn't divine or detect any information about the path โ it simply manipulates the string value. It doesn't map it to any real filesystem object. And it doesn't matter whether or not the file/path named in the input string exists or not. ๐
๐ "strict_path" ๐
Syntax: "strict_path( [string] )"
Works just like "return_path()" except that it's more strict in what it returns. If you pass it a string that doesn't "look" like a path (a string with no directory separators, or that isn't "." or ".."), then this method will return "undef".
If you'd like to get a default path string returned instead of "undef", then you want to use the "default_path()" method instead.
(see also return_path and default_path)
๐ "strip_path" ๐
Syntax: "strip_path( [string] )"
Strips the file path from the file name provided and returns the file name only. โจ
- Given
/kessel/run/12/parsecs, it returnsparsecs - Given
C:\you\scoundrel, it returnsscoundrel
๐ซถ touch
Syntax: touch( [file name] )
Okay so this one is literally just the nix touch command but make it Perl โจ It updates the access time and the modification time of the file you point at to *right now. If that file doesn't exist yet, File::Util will try to create it โ empty, no thoughts, head empty ๐ซ
Heads up bestie: this method fails with a fatal error if system permissions say no to altering or creating the file. So like, know your permissions ๐
Returns 1 if it worked. If it didn't, it fails with an error. Periodt.
๐งน trunc
Syntax: trunc( [file name] )
Truncates [file name] โ which is a fancy way of saying it wipes out, or clobbers, everything inside the file you specified ๐ Returns 1 if it worked. If it didn't work, it fails with a descriptive error message telling you what went wrong. She's honest like that.
๐ unlock_open_handle
Syntax: unlock_open_handle([file handle])
Releases the flock on a file handle you opened with open_handle. Bye bye lock, we hardly knew ye ๐
Returns true on success, false on failure. It will not raise a fatal error if the unlock operation fails โ so if you want drama, you can capture the return value from your call and die() yourself. Failure is basically never gonna happen anyway, because File::Util wouldn't have been able to get a portable lock on the file in the first place.
A few lil scenarios, iykyk:
- If
File::Utilwasn't ever able to lock the file because your operating system said "no <3" (limitations, bestie), a call to this method returns a true value. - If file locking was disabled on the file handle via the
no_lockoption back whenopen_handlewas called, or if file locking was disabled using theuse_flockmethod, or if file locking was disabled on the entireFile::Utilobject at the time of its creation (seenew()), then calling this method has no effect and a true value is returned.
๐ use_flock
Syntax: use_flock( [true / false value] )
Called with no arguments: returns a true or false value reflecting the current use of flock() inside the File::Util object. Vibe check on your lock situation ๐
Called with a true or false value as its single argument: it tells the File::Util object whether or not it should attempt to use flock() in its I/O operations. A true value means "yes queen, use flock() if available", a false value means "nope, we're not doing that". The default is to use flock() when it's available on your system.
๐ซ DON'T USE FLOCK ON NETWORK FILESYSTEMS
If you're working with files on an NFS mount, or a Windows file share, it is quite likely that using flock will be buggy and cause unexpected failures in your program ๐ญ You should not use flock in such situations. Not me warning you twice, but like, I am.
โ ๏ธ A WORD OF CAUTION FOR SOLARIS USERS
File locking has known issues on SOLARIS. Solaris claims to offer a native flock() implementation, but after obtaining a lock on a file, Solaris will very often just silently refuse to unlock it again until your process has completely exited ๐ This is not an issue with File::Util or even with Perl itself. Other programming languages encounter the same problems; it is a system-level issue. So please be aware of this if you are a Solaris user and want to use file locking on your OS.
You may have to explicitly disable file locking completely.
โ๏ธ write_file
Syntax: write_file( [file name] => [string] => { other_options } )
OR: write_file( { file => [file name], content => [string], mode => [mode], other_options } )
Syntax Examples, served fresh ๐:
# get some content (a string returned from a function call, perhaps)
my $answer = ask_commissioner( 'Can he be trusted?' );
$ftl->write_file( 'Harvey_Dent.txt' => $answer );
-OR-
# get some binary content, maybe a picture...
my $binary_data = get_mugshot( alias => 'twoface' );
$ftl->write_file( 'suspect.png' => $binary_data => { binmode => 1 } );
-OR-
# write a file with UTF-8 encoding (unicode character support)
$ftl->write_file( 'encoded.txt' => $encoded_data => { binmode => 'utf8' } );
-OR-
$ftl->write_file(
{
file => '/gotham/city/ballots/Bruce_Wayne.txt',
content => 'Vote for Harvey!',
bitmask => oct 600, # <- secret ballot file permissions
}
);
Attempts to write [string] to [file name] in mode [mode]. If the file does not yet exist it will be created, and it will be created with a bitmask of [bitmask] if you specify a file creation bitmask using the 'bitmask' option โ otherwise the file will be created with the default bitmask of oct 777. The bitmask is combined with the current user's umask, whether you specify a value or not. This is a function of Perl, not File::Util. Noted ๐
[string] should be a string or a scalar variable containing a string. The string can be any type of data โ a binary stream, ascii text with line breaks, whatever your heart desires ๐ Be sure to enable the binmode => 1 option for binary streams, and be sure to specify a value of binmode => 'utf8' for UTF-8 encoded data.
NOTE: you will need Perl version 5.8 or better to use the 'utf8' feature, or your program will fail with an error. No cap.
If specified, the bitmask must be supplied in the form of an octal number, as required by the native perl umask function. See "umask" in perlfunc for more information about the format of the bitmask argument. If the file [file name] already exists then the bitmask argument has no effect and is silently ignored ๐ค
Returns 1 if successful or fails with an error if not successful.
Any non-existent directories in the path preceding the actual file name will be automatically (and silently โ no warnings) created for you, and new directories will be created with a bitmask of [dbitmask], provided you specify a directory creation bitmask with the 'dbitmask' option. She does it all for you, no thank you needed ๐ซถ
If specified, the directory creation bitmask [dbitmask] must be supplied in the form required by the native perl umask function.
If there is a problem while trying to create any preceding directories, the failure results in a fatal error. If all directories preceding the name of the file already exist, the dbitmask argument has no effect and is silently ignored.
๐ mode => 'write' (this is the default mode)
[file name] is created if it does not yet exist. If [file name] already exists then its contents are overwritten with the new content provided. Out with the old โจ
๐ mode => 'append'
[file name] is created if it does not yet exist. If [file name] already exists its contents will be preserved and the new content you provide will be appended to the end of the file. Respecting the existing lore ๐
๐ Options accepted by write_file()
binmode => [ boolean or 'utf8' ]โ Tell File::Util to write the file in binmode (if set to a true boolean:1), or to write the file with UTF-8 encoding, specify a value of"utf8"to this option. (see"binmode"in perlfunc).
You need Perl 5.8 or better to use "utf8" or your program will fail with an error message.
Example Usage:
$ftl->write_file( 'encoded.txt' => $encoded_data => { binmode => 'utf8' } );
empty_writes_OK => booleanโ Allows you to call this method without providing a content argument (it lets you create an empty file without warning you or failing). Be advised that if you enable this option, it will have the same effect as truncating a file that already has content in it (i.e. โ it will "clobber" non-empty files) ๐ So like, be careful bestie.no_lock => booleanโ By default this method will attempt to get a lock on the file while it is being read, following whatever rules are in place for the flock policy established either by default (implicitly) or changed by you in a call toFile::Util::flock_rules()(seeflock_rules()).
This method will not try to get a lock on the file if the File::Util object was created with the option no_lock or if this method is called with the option no_lock enabled.
โ
valid_filename
Syntax: valid_filename( [string] )
For the given string, returns 1 if the string is a legal file name for the system on which the program is running, or returns undef if it is not.
This method does not test for the validity of file paths! It tests for the validity of file names only ๐
(It is used internally to check beforehand if a file name is usable when creating new files, but is also a public method available for external use. So go off, use it ๐)
๐ CONSTANTS ๐
๐ค NL
Syntax: NL
Short for "New Line". Returns the correct new line character (or character sequence) for the system on which your program runs. She adapts ๐
๐ค SL
Syntax: SL
Short for "Slash". Returns the correct directory path separator for the system on which your program runs.
๐ค OS
Syntax: OS
Returns the File::Util keyword for the operating system FAMILY it detected. The keyword for the detected operating system will be one of the following, derived from the contents of $^O, or if $^O can not be found, from the contents of $Config::Config{osname} (see native Config library), or if that doesn't contain a recognizable value, finally falls back to "UNIX".
Generally speaking, Linux operating systems are going to be detected as "UNIX". This isn't a bug ๐ฆ The OS FAMILY to which it belongs uses "UNIX" style filesystem conventions and line endings, which are the relevant things to file handling operations.
- UNIX โ Specifics: OS name
=~ /^(?:darwin|bsdos)/i - CYGWIN โ Specifics: OS name
=~ /^cygwin/i - WINDOWS โ Specifics: OS name
=~ /^MSWin/i - VMS โ Specifics: OS name
=~ /^vms/i - DOS โ Specifics: OS name
=~ /^dos/i - MACINTOSH โ Specifics: OS name
=~ /^MacOS/i - EPOC โ Specifics: OS name
=~ /^epoc/i - OS2 โ Specifics: OS name
=~ /^os2/i
๐ AUTHORS
Tommy Butler <http://www.atrixnet.com/contact>
ยฉ๏ธ COPYRIGHT
Copyright(C) 2001-2013, Tommy Butler. All rights reserved.
๐ LICENSE
This library is free software, you may redistribute it and/or modify it under the same terms as Perl itself. For more details, see the full text of the LICENSE file that is included in this distribution.
โ ๏ธ LIMITATION OF WARRANTY โ ๏ธ
Okay bestie, real talk time, and this part is important so put your phone down for two seconds ๐
This software is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose.
That's the whole vibe. It ships with good intentions and zero promises, no cap ๐ญ If it breaks, it breaks. That's the deal, fr fr.
๐ SEE ALSO ๐
If you're still hungry for more, here's the little friend group of related pages, go give them a read:
File::Util::CookbookFile::Util::Manual::ExamplesFile::Util
And that's a wrap on the whole page, babes ๐ You made it to the end, which is honestly iconic of you โจ Go forth, handle your files, and slay ๐
This version of File::...Manual(3pm) is the one that shipped with perl v5.36.0, dated 2022-11-29 ๐ฆ Read it, love it, bookmark it, text it to your bestie ๐ธ bye pookie ๐
๐ฆ where this page comes from
- debian bookworm: libfile-util-perl 4.201720-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libfile-util-perl 4.201720-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libfile-util-perl 4.201720-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libfile-util-perl 4.201720-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libfile-util-perl 4.201720-2 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms