|
File::Util - Easy, versatile, portable file handling |
bitmaskcan_flockcan_readcan_writecreatedebcdicescape_filenameexistentfile_typeflock_rulesisbinlast_accesslast_modifiedline_countlist_dirload_dirload_filemake_dirmax_divesneeds_binmodenewopen_handlereadlimitreturn_pathsizestrip_pathtruncunlock_open_handleuse_flockwrite_filevalid_filenametype(s) of an existent file
File::Util - Easy, versatile, portable file handling
File::Util provides a comprehensive toolbox of utilities to automate all kinds of common tasks on file / directories. Its purpose is to do so in the most portable manner possible so that users of this module won't have to worry about whether their programs will work on other OSes and machines.
use File::Util; my($f) = File::Util->new();
my($content) = $f->load_file('foo.txt');
$content =~ s/this/that/g;
$f->write_file(
'file' => 'bar.txt',
'content' => $content,
'bitmask' => 0644
);
$f->write_file(
'file' => 'file.bin', 'content' => $binary_content, '--binmode'
);
my(@lines) = $f->load_file('randomquote.txt', '--as-lines');
my($line) = int(rand(scalar @lines));
print $lines[$line];
my(@files) = $f->list_dir('/var/tmp', qw/ --files-only --recurse /);
my(@textfiles) = $f->list_dir('/var/tmp', '--pattern=\.txt$');
if ($f->can_write('wibble.log')) {
my($HANDLE) = $f->open_handle(
'file' => 'wibble.log',
'mode' => 'append'
);
print $HANDLE "Hello World! It's ", scalar localtime;
close $HANDLE
}
my($log_line_count) = $f->line_count('/var/log/httpd/access_log');
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->isbin('my.file');
print "My file was last modified on " .
scalar localtime($f->last_modified('my.file'));
# ...and _lots_ more
To install this module type the following at the command prompt:
perl Makefile.PL make make test make install
On windows machines use nmake rather than make; those running cygwin don't have to worry about this. If you don't know what cygwin is, use nmake and check out http://cygwin.com/ after you're done installing this module if you want to find out.
Exports nothing by default.
The following symbols comprise @File::Util::EXPORT_OK), and as such are
available for import to your namespace only upon request.
can_flock (see can_flock)
ebcdic (see ebcdic)
escape_filename (see escape_filename)
last_access (see last_access)
last_modified (see last_modified)
NL (see NL)
needs_binmode (see needs_binmode)
return_path (see return_path)
SL (see SL)
strip_path (see strip_path)
valid_filename (see valid_filename)
Note: Symbols in @Class::OOorNO|Class::OOorNO::EXPORT_OK are also
available for import.
:all (exports all of @File::Util::EXPORT_OK)
Note: Some of the methods listed will state that they are autoloaded methods. Autloaded methods are not compiled at runtime as part of your process and only get created if called somewhere in your program. (see the AutoLoader manpage.)
Methods listed in alphabetical order.
bitmaskbitmask( [file name] )0644. Otherwise, returns undef if the file does not
exist. This is an autoloaded method.
can_flockcan_flockflock() and if the
Perl process can successfully call it. (see flock in the perlfunc manpage.) Unless
both of these conditions are true a zero value (0) is returned. This is
an autoloaded method. This is a constant subroutine. It accepts no arguments
and will always return the same value for the system on which it is executed.
Note: Perl will try to support or emulate flock whenever it can via
available system calls, namely flock; lockf; or with fcntl.
can_readcan_read( [file name] )This works the same as Perl's built-in -r file test operator,
(see -X in the perlfunc manpage), it's just easier for some people to remember. This
is an autoloaded method.
can_writecan_write( [file name] )This works the same as Perl's built-in -w file test operator,
(see -X in the perlfunc manpage), it's just easier for some people to remember. This
is an autoloaded method.
createdcreated( [file name] )
ebcdicebcdic
escape_filenameescape_filename( [string], [escape char] )/ | * " ? < : > \), are replaced with [escape char] or
``_'' if no [escape char] is specified. Returns an empty string if no
arguments are provided. This is an autoloaded method.
existentexistent( [file name] )This works the same as Perl's built-in -e file test operator,
(see -X in the perlfunc manpage), it's just easier for some people to remember. This
is an autoloaded method.
file_typefile_type( [file name] )The keywords and their definitions appear below; the order of keywords returned is the same as the order in which the are listed 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_rulesflock_rules( [keyword list] )An empty call to this method returns a list of keywords representing the rules that are currently in effect for the object.
Otherwise, a call should include a list with array containing your chosen directive keywords in order of precedence. The rules will be applied in cascading order when a File::Util object attempts to lock a file, so if the actions specified by the first rule don't result in success, the second rule is applied, and so on.
Recognized keywords:
NOBLOCKEXNOBLOCKSHBLOCKEXBLOCKSHFAILWARNIGNOREUNDEFZEROExamples:
flock_rules( qw/ NOBLOCKEX FAIL / );die() with a detailed error message and
a stack trace.
flock_rules( qw/ NOBLOCKEX BLOCKEX FAIL / );flock_rules( qw/ BLOCKEX IGNORE / );This is an autoloaded method.
isbinisbin( [file name] )This works the same as Perl's built-in -B file test operator,
(see -X in the perlfunc manpage), it's just easier for some people to remember. This
is an autoloaded method.
last_accesslast_access( [file name] )
last_modifiedlast_modified( [file name] )
line_countline_count( [file name] )
list_dirlist_dir( [directory name] , [--opts] )list_dir()--dirs-only--files-only--no-fsdots--pattern(ex- '--pattern=\.txt$' returns all file/directory names ending in ``.txt''.
It will match ``foo.txt'', but not ``foo.txt.gz'' because of the ``$'' anchor in the
regular expression passed in.)
or for the opposite effect, '--pattern=.*(?<!\.txt)$' returns all
file/directory names that don't end in ``.txt''
--with-paths--recurse--follow--recurse
--dirs-as-ref--files-as-ref--dirs-as-ref was also used).
--as-ref--sl-after-dirs--ignore-caseIf you'd like the directory contents returned by this method to be sorted without regard to case , use this flag.
--count-only
load_dirload_dir( [directory name] , [--ds-type] )The type of data structure returned is determined by the optional data-type switch. Only one option may be used for a given call to this method. Recognized options are listed below.
load_dir()--as-list--as-listref--as-hashref *(default)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 readlimit()) entry below will be applied to the files opened by this method as well. Adjust the readlimit as necessary.
my($files) = $fu->load_dir('directory/to/load/');
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_fileload_file( [file name] , [--opts] )load_file( 'FH' => [file handle reference] , [--opts] )CORE::read() and the data obtained by the read will be returned in a string.
If you desire the contents of the file (or file handle data) in a list of
lines instead of a single string, this can be accomplished through the use
of the --as-lines flag (see below).
load_file()--as-linesload_file will return an ordered
list of strings, each of which is a line from the file [file name]. The lines
are returned in the order they are read, from the beginning of the file to the
end.
This is not the default behavior. The default behavior is for load_file to
return a single string containing the entire contents of the file, including
line break characters.
--no-lockThis 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 was called with the
option --no-lock.
This method will automatically call binmode() on binary files for you. If you
pass in a filehandle instead of a file name you do not get this automatic
check performed for you. In such a 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.
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 readlimit()) entry below will be applied to the files opened by this method as well. Adjust the readlimit as necessary.
make_dirmake_dir( [new directory name] , [bitmask], [--opts] )As mentioned above, the recursive creation of directories is transparently
handled for you. This means that 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, the directory ``/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 0777.
Upon successful creation of the [new directory name], the [new directory name] is returned to the caller.
make_dir()--if-not-existsIf a call to this method is made without the --if-not-exists flag and the
directory specified as [new directory name] does in fact exist, an error will
result as it is impossible to create a directory that already exists.
This is an autoloaded method.
max_divesmax_dives( [integer] )File::Util::list_dir(). The default is 1000. If the number is
exceeded, the File::Util object will fail with a diagnostic error message.
When called with an argument, 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 message.
(see list_dir)
This is an autoloaded method.
needs_binmodeneeds_binmodebinmode()
(a built-in function) be called on open file handles, or returns 0 if not.
(see binmode in the perlfunc manpage.) This is an autoloaded method. This is a constant
subroutine. It accepts no arguments and will always return the same value for
the system on which it is executed.
newnew( ['parameters' => 'values', etc], [--flags] )new()File::Util::new method instruct the
new object that it should never attempt to use flock() in it's I/O
operations. The default is to use flock() when available on your system.
Specify this option with a true or false value, true to use flock(), false
to not use it.
new()--fatals-as-warningundef
instead of the value(s) that would normally be returned by the call, and to
send an error message to STDERR as well.
--fatals-as-statusundef
instead of the value(s) that would normally be returned by the call.
--fatals-as-errmsgvalue(s) that would normally be returned by the call.
open_handleopen_handle('file' => [file name], [--opts])open_handle('file' => [file name], 'mode' => [mode], [--opts])open_handle('file' => [file name], 'mode' => [mode], 'bitmask' => [bitmask], [--opts])open_handle('file' => [file name], 'mode' => [mode], 'bitmask' => [bitmask], 'dbitmask' => [bitmask], [--opts])You will need to remember to call close() on the filehandle yourself, at
your own discretion. Leaving filehandles open is not a good practice, and
is not recommended. see close in the perlfunc manpage).
Once you have the file handle you would use it as you would use any file handle.
Remember that unless you specifically turn file locking off when the
File::Util object is created (see (see new) or by using the
--no-lock flag when calling open_handle, that file locking is going to
automagically be handled for you behind the scenes, so long as your OS supports
file locking of any kind at all. Great! It's very convenient for you to not
have to worry about portably taking care of file locking between one
application and the next; by using File::Util in all of them, you know
that you're covered.
A slight inconvenience for the price of a larger set of features (compare
write_file to this method)
you will 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. In order to release the file lock
on your file handle, call unlock_open_handle() on it.
Otherwise the lock will remain for the life of your process. If you don't
want to use the free portable file locking, remember the --no-lock flag,
which will turn off file locking for your open handle. Seldom, however, should
you ever opt to not use file locking unless you really know what you are doing.
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 0777.
If specified, the bitmask must be supplied in the form required by the native perl umask function. see umask in the perlfunc manpage 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.
Any non-existent directories in the path preceeding 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 is an error while trying to create any preceeding directories, the failure results in a fatal error with a diagnostic error message. If all directories preceeding the name of the file already exist, the dbitmask argument has no effect and is silently ignored.
open_handle() is to open file handles using Perl's
native open() (see open in the perlfunc manpage). Unless you use the
--use-sysopen flag, the following modes and only these modes are valid.
'mode' => 'read''mode' => 'write' (this is the default mode)'mode' => 'append'File::Util to open your handle using CORE::sysopen
instead of using the native Perl CORE::open(). This is accomplished by
passing in the --use-sysopen flag. Using this feature opens up more
possibilities as far as the open modes you can choose from, but also carries
with it a few caveats so you have to be careful, just as you'd have to be a
little more careful when using sysopen() anyway.
Specifically you need to remember that when using 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 print to them as you normally
would print to a file handle. You have to use syswrite() instead. The
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 type of sys* commands on the filehandle instead of
their native Perl equivalents.
(see sysopen in the perlfunc manpage, syswrite in the perlfunc manpage, sysseek in the perlfunc manpage, sysread in the perlfunc manpage)
That said, here are the different modes you can choose from to get a file handle
when using the --use-sysopen flag. Remember that these won't work unless
you use the flag, and will 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''mode' => 'rwupdate''mode' => 'rwclobber'open_handle() using this option, your file WILL be wiped out.
If the file does not exist yet, it will be created for you.
'mode' => 'rwappend'Remember to use sysread() and not plain read() when reading those
sysopen()'d filehandles!
open_handle()--binmode--no-lockThis 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-sysopenopen() command, File::Util
will open the file with the sysopen() command. You will have to remember
that your filehandle is a sysopen()'d one, and that you will not be able to
use native Perl I/O functions on it. You will have to use the sys*
equivalents. See the perlopentut manpage for a more in-depth explanation of why you
can't mix native Perl I/O with system I/O.
This is an autoloaded method.
readlimitreadlimit( [integer] )This value can be modified by calling this method with an integer value reflecting the new limit you want to impose, in bytes. 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.
This is an autoloaded method.
return_pathreturn_path( [string] )This is an autoloaded method.
sizesize( [file name] )0 if the file is
empty, returns undef if the file does not exist.
This is an autoloaded method.
strip_pathstrip_path( [string] )
trunctrunc( [file name] )1 if successful. If unsuccessful, fails with a
descriptive error message about what went wrong.
This is an autoloaded method.
unlock_open_handleunlock_open_handle([file handle])Returns true on success, false on failure. Will not raise a fatal error if
the unlock operation fails. You can capture the return value from your call
to this method and die() if you so desire. Failure is not ever very likely,
or File::Util wouldn't have been able to get a portable lock on the file
in the first place.
If File::Util wasn't able to ever lock the file due to limitations of your
operating system, a call to this method will return a true value.
If file locking has been disabled on the file handle via the --no-lock flag
at the time open_handle was called, or if file locking was
disabled using the use_flock method, or if file locking was
disabled on the entire File::Util object at the time of its creation
(see new()), calling this method will have no effect and a true value
will be returned.
This is an autoloaded method, due to open_handle also being autoloaded.
use_flockuse_flock( [true / false value] )flock() within the File::Util object.
When called with a true or false value as its single argument, this method
will tell the File::Util object whether or not it should attempt to use
flock() in its I/O operations. A true value indicates that the File::Util
object will use flock() if available, a false value indicates that it will
not. The default is to use flock() when available on your system.
This is an autoloaded method.
write_filewrite_file('file' => [file name], 'content' => [string], [--opts])write_file('file' => [file name], 'content' => [string], 'mode' => [mode], [--opts])write_file('file' => [file name], 'content' => [string], 'mode' => [mode], 'bitmask' => [bitmask], [--opts])write_file('file' => [file name], 'content' => [string], 'mode' => [mode], 'bitmask' => [bitmask], 'dbitmask' => [bitmask], [--opts])'bitmask' option,
otherwise the file will be created with the default bitmask of 0777.
[string] should be a string or a scalar variable containing a string. The
string can be any type of data, such as a binary stream, or ascii text with
line breaks, etc. Be sure to pass in the --binmode flag for binary streams.
If specified, the bitmask must be supplied in the form required by the native perl umask function. see umask in the perlfunc manpage 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 (fatal) with an error message if not successful.
Any non-existent directories in the path preceeding 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 is an error while trying to create any preceeding directories, the failure results in a fatal error with a diagnostic error message. If all directories preceeding the name of the file already exist, the dbitmask argument has no effect and is silently ignored.
'mode' => 'write' (this is the default mode)'mode' => 'append'write_file()--binmode--no-lockThis 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.
valid_filenamevalid_filename( [string] )
NLNL
SLSL
OSOS$^O, or if $^O can not be found, from the contents of
$Config::Config{osname} (see native the Config manpage 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.
use File::Util;
my($f) = File::Util->new();
# option --no-fsdots excludes "." and ".." from the list
my(@dirs_and_files) = $f->list_dir('/foo','--no-fsdots');
use File::Util;
my($f) = File::Util->new();
my(@dirs_and_files) = $f->list_dir('/foo','--recurse');
use File::Util;
my($f) = File::Util->new();
my(@dirs_and_files) = $f->list_dir('/foo','--files-only');
use File::Util;
my($f) = File::Util->new();
my(@dirs_and_files) = $f->list_dir('/foo','--dirs-only');
use File::Util;
my($f) = File::Util->new();
my(@dirs_and_files) = $f->list_dir('/foo', qw/--no-fsdots --count-only/);
use File::Util;
my($f) = File::Util->new();
my($dirs,$files) = $f->list_dir('/foo', '--as-ref');
-OR-
my($dirs,$files) = $f->list_dir('.', qw/--dirs-as-ref --files-as-ref/);
use File::Util;
my($f) = File::Util->new();
my($contents) = $f->load_file('filename');
use File::Util;
my($f) = File::Util->new();
my(@contents) = $f->load_file('filename','--as-lines');
use File::Util;
my($f) = File::Util->new();
my($FH_REF) = $f->open_handle(
'file' => 'new_filename',
'mode' => 'read'
);
use File::Util;
my($f) = File::Util->new();
my($FH_REF) = $f->open_handle(
'file' => 'new_filename',
'mode' => 'write'
);
use File::Util;
my($content) = 'Pathelogically Eclectic Rubbish Lister';
my($f) = File::Util->new();
$f->write_file('file' => 'a new file.txt', 'content' => $content);
# optionally specify a creation bitmask when writing to a new file
$f->write_file(
'file' => 'a new file.txt',
'bitmask' => 0777,
'content' => $content
);
use File::Util;
my($content) = 'Pathelogically Eclectic Rubbish Lister';
my($f) = File::Util->new();
$f->write_file(
'file' => 'a new file.txt',
'mode' => 'append',
'content' => $content
);
use File::Util qw( valid_filename );
if (valid_filename("foo?+/bar~@/#baz.txt")) {
print "file name is valid"
else {
print "file name contains illegal characters"
}
-OR-
use File::Util;
print File::Util->valid_filename("foo?+/bar~@/#baz.txt") ? 'ok' : 'bad';
-OR-
use File::Util;
my($f) = File::Util->new();
print $f->valid_filename("foo?+/bar~@/#baz.txt") ? 'ok' : 'bad';
use File::Util;
my($f) = File::Util->new();
my($linecount) = $f->line_count('foo.txt');
use File::Util; my($f) = File::Util->new();
# On Windows
# (prints "hosts")
my($path) = $f->strip_path('C:\WINDOWS\system32\drivers\etc\hosts');
# On Linux/Unix
# (prints "perl")
print $f->strip_path('/usr/bin/perl');
# On a Mac
# (prints "baz")
print $f->strip_path('foo:bar:baz');
use File::Util; my($f) = File::Util->new();
# On Windows
# (prints "C:\WINDOWS\system32\drivers\etc")
my($path) = $f->strip_path('C:\WINDOWS\system32\drivers\etc\hosts');
# On Linux/Unix
# (prints "/usr/bin")
print $f->strip_path('/usr/bin/perl');
# On a Mac
# (prints "foo:bar")
print $f->strip_path('foo:bar:baz');
use File::Util qw( can_flock ); print can_flock;
-OR-
print File::Util->can_flock;
-OR-
my($f) = File::Util->new();
print $f->can_flock;
use File::Util qw( needs_binmode ); print needs_binmode;
-OR-
use File::Util;
print File::Util->needs_binmode;
-OR-
use File::Util;
my($f) = File::Util->new();
print $f->needs_binmode;
use File::Util;
my($f) = File::Util->new();
my($is_readable) = $f->can_read('foo.txt');
use File::Util;
my($f) = File::Util->new();
my($is_writable) = $f->can_write('foo.txt');
use File::Util; my($f) = File::Util->new();
# prints "C__WINDOWS_system32_drivers_etc_hosts"
print $f->escape_filename('C:\WINDOWS\system32\drivers\etc\hosts');
# prints "baz)__@^"
# (strips the file path from the file name, then escapes it
print $f->escape_filename(
'/foo/bar/baz)?*@^',
'--strip-path'
);
# prints "_foo_!_@so~me#illegal$_file&(name" # (yes, that is a legal filename) print $f->escape_filename(q[\foo*!_@so~me#illegal$*file&(name]);
use File::Util qw( ebcdic ); print ebcdic;
-OR-
use File::Util;
print File::Util->ebcdic;
-OR-
use File::Util;
my($f) = File::Util->new();
print $f->ebcdic;
type(s) of an existent file
use File::Util qw( file_type );
print file_type('foo.exe');
-OR-
use File::Util;
print File::Util->file_type('bar.txt');
-OR-
use File::Util;
my($f) = File::Util->new();
print $f->file_type('/dev/null');
use File::Util qw( bitmask );
print bitmask('/usr/sbin/sendmail');
-OR-
use File::Util;
print File::Util->bitmask('C:\COMMAND.COM');
-OR-
use File::Util;
my($f) = File::Util->new();
print $f->bitmask('/dev/null');
use File::Util qw( created );
# prints "Fri Aug 22 14:57:58 2003" on my system
print scalar localtime created('/usr/bin/exim');
-OR-
use File::Util;
# prints "Fri Apr 23 22:22:00 1999" on my system
print scalar localtime File::Util->created('C:\COMMAND.COM');
-OR-
use File::Util;
my($f) = File::Util->new();
# prints "Thu Jul 24 05:51:30 2003" on my system
print scalar localtime $f->created('/bin/less');
use File::Util qw( last_access );
# prints "Fri Sep 5 04:11:41 2003" on my system
print scalar localtime last_access('/usr/bin/exim');
-OR-
use File::Util;
# prints "Mon Sep 22 18:51:53 2003" on my system
print scalar localtime File::Util->last_access('C:\COMMAND.COM');
-OR-
use File::Util;
my($f) = File::Util->new();
# prints "Mon Sep 22 03:14:38 2003" on my system
print scalar localtime $f->last_access('/bin/less');
use File::Util qw( last_modified );
# prints "Fri Sep 5 01:14:51 2003" on my system
print scalar localtime last_modified('/usr/bin/exim');
-OR-
use File::Util;
# prints "Fri Apr 23 22:22:00 1999" on my system
print scalar localtime File::Util->last_modified('C:\COMMAND.COM');
-OR-
use File::Util;
my($f) = File::Util->new();
# prints "Fri Sep 5 01:15:17 2003" on my system
print scalar localtime $f->last_modified('/bin/less');
use File::Util;
my($f) = File::Util->new();
$f->make_dir('/var/tmp/tempfiles/foo/bar/');
# optionally specify a creation bitmask to be used in directory creations
$f->make_dir('/var/tmp/tempfiles/foo/bar/',0755);
use File::Util;
my($f) = File::Util->new();
$f->trunc('/foo/bar/baz.tmp');
use File::Util qw( SL ); print SL;
-OR-
use File::Util;
print File::Util->SL;
-OR-
use File::Util;
my($f) = File::Util->new();
print $f->SL;
use File::Util qw( NL ); print NL;
-OR-
use File::Util;
print File::Util->NL;
-OR-
use File::Util;
my($f) = File::Util->new();
print $f->NL;
# Code changes the file suffix of all files in a directory ending in # *.foo so that they afterward end in *.bar
use strict; use vars qw( $dir ); use File::Util qw( NL SL );
my($f) = File::Util->new(); my($dir) = '../wibble'; my($old) = 'foo'; my($new) = 'bar'; my(@files) = $f->list_dir($dir, '--files-only');
foreach (@files) {
# don't change the file suffix unless it is *.foo
if ($_ =~ /\.$old$/o) {
my($newname) = $_; $newname =~ s/\.$old/\.$new/;
if (rename($dir . SL . $_, $dir . SL . $newname)) {
print qq[$_ -> $newname], NL
}
else { warn <<__ERR__ }
Couldn't rename "$_" to "$newname"!
__ERR__
}
else { print <<__NOCHANGE__ }
File retained as "$_"
__NOCHANGE__
}
# Code does a batch find or search and replace for all files in a given # directory, recursively or non-recursively based on choices set forth # in the code.
use strict; use File::Util qw( NL SL );
# will get search pattern from file named below use constant SFILE => './sr/searchfor';
# will get replace pattern from file named below use constant RFILE => './sr/replacewith';
# will perform batch operation in directory named below use constant INDIR => '/foo/bar/baz';
# specify whether the operation will do a find or a search and replace use constant RMODE => [qw| read-only write |]->[1];
# set the options for the search (will or will not recurse, etc) my(@opts) = [qw/ --files-only --with-paths --recurse /]->[0,1];
# create new File::Util object, set File::Util to send a warning for
# fatal errors instead of dieing
my($f) = File::Util->new('--fatals-as-warning');
my($rstr) = $f->load_file(RFILE);
my($spat) = quotemeta($f->load_file(SFILE)); $spat = qr/$spat/;
my($gsbt) = 0;
my($action) = RMODE eq 'read-only' ? 'detections' : 'substitutions';
my(@files) = $f->list_dir(INDIR, @opts);
for (my($i) = 0; $i < @files; ++$i) {
next if $f->isbin($files[$i]);
my($sbt) = 0; my($file) = $f->load_file($files[$i]);
$file =~ s/$spat/++$sbt;++$gsbt;$rstr/ge;
$f->write_file('file' => $files[$i], 'content' => $file)
if RMODE eq 'write';
print $sbt ? (qq[$sbt $action in $files[$i]] . NL) : '';
}
print( NL . <<__DONE__ . NL x 2) and exit;
$gsbt $action in ${\scalar(@files)} files.
__DONE__
use strict; use vars qw( $a $b );
use File::Util qw( NL );
my($ind) = '';
my($f) = File::Util->new();
my(@o) = qw(
--with-paths
--sl-after-dirs
--no-fsdots
--files-as-ref
--dirs-as-ref
);
my($filetree) = {};
my($treetrunk) = '/var/';
my($subdirs,$sfiles) = $f->list_dir($treetrunk, @o);
$filetree = [{
$treetrunk => [ sort({ uc $a cmp uc $b } @$subdirs, @$sfiles) ]
}];
descend($filetree->[0]{ $treetrunk },scalar(@$subdirs));
walk(@$filetree);
sub descend {
my($parent,$dirnum) = @_;
for (my($i) = 0; $i < $dirnum; ++$i) {
my($current) = $parent->[$i]; next unless -d $current;
my($subdirs,$sfiles) = $f->list_dir($current, @o);
map { $_ = $f->strip_path($_) } @$sfiles;
splice(@$parent,$i,1,{
$current => [ sort({ uc $a cmp uc $b } @$subdirs, @$sfiles) ]
});
descend($parent->[$i]{ $current },scalar(@$subdirs));
}
$parent
}
sub walk {
my($dir) = shift(@_);
foreach (@{ [ %$dir ]->[1] }) {
my($mem) = $_;
if (ref($mem) eq 'HASH') {
print($ind . $f->strip_path([ %$mem ]->[0]) . '/',NL);
$ind .= ' ' x 3;
walk($mem);
$ind = substr($ind,3);
} else { print($ind . $mem,NL) }
}
}
Send bug reports to the AUTHOR. There are no known bugs at this time.
Add full support for PerlIO layers in File::Util::open_handle() and possibly
File::Util::write_file().
Tommy Butler <cpan@atrixnet.com>
Copyright(C) 2001-2007, Tommy Butler. All rights reserved.
This library is free software, you may redistribute and/or modify it under the same terms as Perl itself.
the File::Slurp manpage, the Exception::Handler manpage, the Class::OOorNO manpage
|
File::Util - Easy, versatile, portable file handling |