File::Util(3pm)
π File::Util β the manual page, bestie edition π
okay so you found the File::Util(3pm) page, and honestly? you're about to have the best time. it's the User Contributed Perl Documentation, it's iconic, and it's about to make your file handling so much easier. buckle up. π
β¨ NAME β¨
File::Util β Easy, versatile, portable file handling
like. that's the whole vibe. easy. versatile. portable. slay. π
πΈ VERSION πΈ
version 4.201720
π¦ DESCRIPTION π¦
File::Util hands you a whole comprehensive toolbox of utilities that automates basically every common task you'd ever wanna do on files and directories. and the whole point of it is that it does this in the most portable way possible, so you, my dear programmer bestie, never have to sit there worrying whether your program is gonna work on some other operating system or architecture. it works on Linux, Windows, Mac, BSD, Unix and others. fr fr. π
File::Util is written purely in Perl, so you need no compiler or make utility on your system to install it and run it. it loads a minimal amount of code when you use it, and it only pulls in support for the lesser-used methods on demand (main character energy: shows up exactly when needed, never extra). and it has no dependencies other than what already comes installed with Perl itself. π
File::Util also aims to be as backward compatible as possible, running without problems on Perl installations as old as 5.006. that said, you're encouraged to run File::Util on Perl version 5.8 and above. (do it. it's what she deserves. π)
after you finish browsing this document, please go look at the other documentation. (See the DOCUMENTATION section below.) there's so much more where this came from, i'm literally obsessed.
π SYNOPSIS π
# use File::Util in your program
use File::Util;
# create a new File::Util object
my $f = File::Util->new();
# read file into a variable
my $content = $f->load_file( 'some_file.txt' );
# write content to a file
$f->write_file( 'some_other_file.txt' => 'Hello world!' );
# get the contents of a directory, 3 levels deep
my @songs = $f->list_dir( '~/Music' => { recurse => 1, max_depth => 3 } );
like?? look at that. three lines and you're done. it's giving effortless. β¨
π DOCUMENTATION π
you can do so much more with File::Util than the examples above, bestie. for an explanation of all the features available to you, take a look at these other reference materials:
- Examples β the
File::Util::Manual::Examplesdocument has a long list of small, reusable code snippets and techniques to use in your own programs. this is the "cheat sheet", and it's a great place to get started quickly. almost everything you need is here. ngl, start here. - Complete API Reference β the
File::Util::Manualis the complete reference document explaining every available feature and object method. use this to look up the full information on any given feature when the examples aren't enough. - Cookbook β the
File::Util::Cookbookcontains examples of complete, working programs that useFile::Utilto easily accomplish tasks which require file handling.
π BASIC USAGE π
π Getting Started π
# use File::Util in your program
use File::Util;
# ...you can optionally enable File::Util's diagnostic error messages:
# (see File::Util::Manual section regarding diagnostics)
use File::Util qw( :diag );
# create a new File::Util object
my $f = File::Util->new();
# ...you can enable diagnostics for individual objects:
$f = File::Util->new( diag => 1 );
π File Operations π
# load file content into a scalar variable as raw text
my $content = $f->load_file( 'somefile.txt' );
# read a binary file the same way
my $binary_content = $f->load_file( 'barking-cat.mp4' );
# write a raw text file
$f->write_file( 'somefile.txt' => $content );
# ...and write a binary file, using some other options as well
$f->write_file(
'llama.jpg' => $picture_data => { binmode => 1, bitmask => oct 644 }
);
# ...or write a file with UTF-8 encoding (unicode support)
$f->write_file( 'encoded.txt' => qq(\x{c0}) => { binmode => 'utf8' } );
# load a file into an array, line by line
my @lines = $f->load_file( 'file.txt' => { as_lines => 1 } );
# see if you have permission to write to a file, then append to it
if ( $f->is_writable( 'captains.log' ) ) {
my $fh = $f->open_handle( 'captains.log' => 'append' );
print $fh "Captain's log, stardate 41153.7. Our destination is...";
close $fh or die $!;
}
else { # ...or warn the crew
warn "Trouble on the bridge, the Captain can't access his log!";
}
# get the number of lines in a file
my $log_line_count = $f->line_count( '/var/log/messages' );
π§ File Handles π§
# get an open file handle for reading
my $fh = $f->open_handle( 'Ian likes cats.txt' => 'read' );
while ( my $line = <$fh> ) { # read the file, line by line
# ... do stuff
}
# get an open file handle for writing the same way
$fh = $f->open_handle( 'John prefers dachshunds.txt' => 'write' );
# You add the option to turn on UTF-8 strict encoding for your reads/writes
$fh = $f->open_handle(
'John prefers dachshunds.txt' => 'write' => { binmode => 'utf8' }
);
print $fh "Bob is happy! \N{U+263A}"; # << unicode smiley face!
# you can use sysopen to get low-level with your file handles if needed
$fh = $f->open_handle(
'alderaan.txt' => 'rwclobber' => { use_sysopen => 1 }
);
syswrite $fh, "that's no moon";
# ...You can use any of these syswrite modes with open_handle():
# read, write, append, rwcreate, rwclobber, rwappend, rwupdate, and trunc
PLEASE NOTE that as of Perl 5.23, it is deprecated to mix system IO (sysopen/syswrite/sysread/sysseek) with utf8 binmode (see perldoc perlport). as such,File::Utilwill no longer allow you to do this after version4.132140. please see notes on UTF-8 and encoding further below.
# ...THIS WILL NOW FAIL!
$f->open_handle(
'somefile.txt' => 'write' => { use_sysopen => 1, binmode => 'utf8' }
);
like. don't do it. it will NOT work. π
π Directories π
# get a listing of files, recursively, skipping directories
my @files = $f->list_dir( '/var/tmp' => { files_only => 1, recurse => 1 } );
# get a listing of text files, recursively
my @textfiles = $f->list_dir(
'/var/tmp' => {
files_match => qr/\.txt$/,
files_only => 1,
recurse => 1,
}
);
# walk a directory, using an anonymous function or function ref as a callback
$f->list_dir( '/home/larry' => {
recurse => 1,
callback => sub {
my ( $selfdir, $subdirs, $files ) = @_;
# do stuff ...
},
} );
# get an entire directory tree as a hierarchal datastructure reference
my $tree = $f->list_dir( '/my/podcasts' => { as_tree => 1 } );
π Getting Information About Files π
print 'My file has a bitmask of ' . $f->bitmask( 'my.file' );
print 'My file is a ' . join(', ', $f->file_type( 'my.file' )) . " file.";
warn 'This file is binary!' if $f->is_bin( 'my.file' );
print 'My file was last modified on ' .
scalar localtime $f->last_modified( 'my.file' );
β Getting Information About Your System's IO Capabilities β
# Does your running Perl support unicode?
print 'I support unicode' if $f->can_utf8;
# Can your system use file locking?
print 'I can use flock' if $f->can_flock;
# The correct directory separator for your system
print 'The correct directory separator for this system is ' . $f->SL;
# Does your platform require binmode for all IO?
print 'I always need binmode' if $f->needs_binmode;
# Is your system an EBCDIC platform? (see perldoc perlebcdic)
print 'This is an EBCDIC platform, so be careful!' if $f->EBCDIC;
...See the File::Util::Manual for more details and features like advanced pattern matching in directories, callbacks, directory walking, user-definable error handlers, and more. iykyk. π
π File Encoding and UTF-8 π
if you wanna read/write in UTF-8, you can do that:
$ftl->load_file( 'file.txt' => $content => { binmode => 'utf8' } );
$ftl->write_file( 'file.txt' => $content => { binmode => 'utf8' } );
$ftl->open_handle( 'file.txt' => 'read' => { binmode => 'utf8' } );
# ...and so on
only use binmode => 'utf8' for text. do not use it for binary. periodt.
encoding and IO layers (sometimes called disciplines) can become complex. it's not something you usually need to worry about unless you wish to really fine tune File::Util's behavior beyond what are very suitable, portable defaults, or accomplish very specific tasks like encoding conversions.
you're free to specify any binmode you like, or let File::Util use the system's default IO layering. it will automatically use the ":raw" pseudo layer when reading files that are binary, unless specifically told to use something different.
you can control things as shown in the examples below:
$ftl->load_file( 'file.txt' => $content => { binmode => SPEC } );
$ftl->write_file( 'file.txt' => $content => { binmode => SPEC } );
$ftl->open_handle( 'file.txt' => 'read' => { binmode => SPEC } );
...where SPEC is one or more of any supported IO layers on your system. examples might include:
':raw'':unix'':crlf'':stdio'':encoding(ENCODING)'with ENCODING's likeiso-8859-1,shiftjis, etc- ...and much more
you can learn about the IO layers available to you and what they do in the PerlIO perldoc. available options have increased over the years, and are likely subject to continued evolution. consult the PerlIO and Encode documentation as your authoritative source of info on what layers to use. π¦
π₯ PERFORMANCE π₯
File::Util consists of a set of smaller modules, but only loads the ones it needs when it needs them. it offers a comparatively fast load-up time, so using File::Util doesn't bloat your code's resource footprint. not me being efficient AND pretty. π
additionally, File::Util has been optimized to run fast. in many scenarios it does more and still out-performs other popular IO modules. Benchmarking tools are included as part of the File::Util installation package. π₯
(see the benchmarking and profiling scripts that are included as part of this distribution.)
π§ METHODS π§
File::Util exposes the following public methods. bestie, they're ALL here π
Each of which are covered in the File::Util::Manual, which has more room for the detailed explanation that is provided there.
This is just an itemized table of contents for HTML POD readers. For those viewing this document in a text terminal, open perldoc to the "File::Util::Manual".
atomize_pathβ (seeatomize_path)bitmaskβ (seebitmask)can_flockβ (seecan_flock)can_utf8β (seecan_utf8)createdβ (seecreated)default_pathβ (seedefault_path)diagnosticβ (seediagnostic)ebcdicβ (seeebcdic)escape_filenameβ (seeescape_filename)existentβ (seeexistent)file_typeβ (seefile_type)flock_rulesβ (seeflock_rules)is_binβ (seeis_bin)is_readableβ (seeis_readable)is_writableβ (seeis_writable)last_accessβ (seelast_access)last_changedβ (seelast_changed)last_modifiedβ (seelast_modified)line_countβ (seeline_count)list_dirβ (seelist_dir)load_dirβ (seeload_dir)load_fileβ (seeload_file)make_dirβ (seemake_dir)abort_depthβ (seeabort_depth)needs_binmodeβ (seeneeds_binmode)newβ (seenew)onfailβ (seeonfail)open_handleβ (seeopen_handle)read_limitβ (seeread_limit)return_pathβ (seereturn_path)sizeβ (seesize)split_pathβ (seesplit_path)strict_pathβ (seestrict_path)strip_pathβ (seestrip_path)touchβ (seetouch)truncβ (seetrunc)unlock_open_handleβ (seeunlock_open_handle)use_flockβ (seeuse_flock)valid_filenameβ (seevalid_filename)write_fileβ (seewrite_file)
π EXPORTED SYMBOLS π
Exports nothing by default. File::Util fully respects your namespace, like the polite icon it is π. You can, however, ask it for certain things (below) π
β¨ EXPORT_OK β¨
The following symbols comprise @File::Util::EXPORT_OK, and as such are available for import to your namespace only upon request. They can be used either as object methods or like regular subroutines in your program.
atomize_pathcan_flockcan_utf8createddefault_pathdiagnosticebcdicescape_filenameexistentfile_typeis_binis_readableis_writablelast_accesslast_changedlast_modifiedneeds_binmodestrict_pathreturn_pathsizesplit_pathstrip_pathvalid_filename- NL and S L
To get any of these functions/symbols into your namespace without having to use them as object methods, use this kind of syntax:
use File::Util qw( strip_path return_path existent size );
my $file = $ARGV[0];
my $fname = strip_path( $file );
my $path = return_path( $file );
my $size = size( $file );
print qq(File "$fname" exists in "$path", and is $size bytes in size)
if existent( $file );
π EXPORT_TAGS π
:allβ imports all of@File::Util::EXPORT_OKto your namespace:diagβ imports nothing to your namespace, it just enables diagnostics
You can use these tags alone, or in combination with other symbols as shown above. mix and match, it's your world π«Ά
πΈ PREREQUISITES πΈ
None. There are no external prerequisite modules.
File::Util only depends on modules that are part of the Core Perl distribution, and you don't need a compiler on your system to install it. no compiling era, we love to see it β¨
File::Util recommends Perl 5.8.1 or better ...
You can technically run File::Util on older versions of Perl 5, but it isn't recommended, especially if you want unicode support and wish to take advantage of File::Util's ability to read and write files using UTF-8 encoding.
Unicode::UTF8 is also recommended and helps speed things up in several places where you might choose to use unicode as described elsewhere in the File::Util::Manual. π₯
π¦ INSTALLATION π¦
To install this module type the following at the command prompt:
perl Build.PL
perl Build
perl Build test
sudo perl Build install
On Windows systems, the "sudo" part of the command may be omitted, but you will need to run the rest of the install command with Administrative privileges π
π BUGS π
Send bug reports and patches to the CPAN Bug Tracker for File::Util at rt.cpan.org https://rt.cpan.org/Dist/Display.html?Name=File%3A%3AUtil
ngl if you find a bug, tell the authors. they're nice, promise π
π SUPPORT π
If you want to get help, contact the authors (links below in AUTHORS section)
I fully endorse http://www.perlmonks.org as an excellent source of help with Perl in general. π
π CONTRIBUTING π
The project website for File::Util is at https://github.com/tommybutler/file-util/wiki
The git repository for File::Util is on Github at https://github.com/tommybutler/file-util
Clone it at git://github.com/tommybutler/file-util.git
This project was a private endeavor for too long so don't hesitate to pitch in. your PR could be THE moment π
β CONTRIBUTORS β
The following people have contributed to File::Util in the form of feedback, encouragement, recommendations, testing, or assistance with problems either on or offline in one form or another. Listed in no particular order:
- John Fields
jfields.cpan.org@spammenot.com - BrowserUk
browseruk@cpan.org - Ricardo SIGNES
rjbs@cpan.org - Matt S Trout
perl-stuff@trout.me.uk - Nicholas Perez
nperez@cpan.org - David Golden
dagolden@cpan.org
π AUTHORS π
Tommy Butler http://www.atrixnet.com/contact
Others Welcome! π«Ά
π 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 β¨
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.
This disclaimer applies to every part of the File::Util distribution. fr fr, read that one twice π
π§ SEE ALSO π§
The rest of the documentation: File::Util::Manual, File::Util::Manual::Examples, File::Util::Cookbook
Other Useful Modules that do similar things: File::Slurp, File::Spec, File::Find::Rule, Path::Class, Path::Tiny
and that's the whole page, bestie!! π this doc shipped as perl v5.36.0, dated 2022-11-29, under the name File::Util(3pm) β go read the Manual next, it's the director's cut π¬β¨
π¦ 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