CleanCode Perl Libraries
Multi-Lingual Library Maintainability
available: Perl not available: Java not available: JavaScript not available: Certified
Class
not available: Testable
Class
not available: Standalone
Mode
not available: Diagnostic
Enabled

NAME

File::Handy - Provides assorted file manipulation functions.

SYNOPSIS

        use File::Handy qw(appendFile copyDir datedFileName
                getLatestFileName incrFile newer readFile writeFile);
        $text = readFile("filename", 1);
        @lines = readFile("filename", 1);
        $success = writeFile("filename", $text, "bak", 1);
        writeFile("filename", $text, "Copy_of_%s");
        appendFile("filename", $text, 1);
        $incrOK = incrFile("filename");
        if (newer("file.in", "file.out")) { ... }
        $newName = datedFileName("dir/stuff.txt");
        $newName = datedFileName("stuff");
        $newName = datedFileName("stuff.htm", "%s_%d%d%d.%s");
        $success = copyDir("/abc", "home/foo", ["gif","jpg"]);
        copyDir($sourceDir, $targetDir, "doc");
        copyDir($sourceDir, $targetDir);
        $latestStockFile = getLatestFileName("dir/files", "stocks");
        $fname = getLatestFileName($fname, 'A.*\.txt', "2002/11/20");
        $permString = permsToString($fname);
        print catPath("/root", "filename");
        my @files = getMatchingFiles($dir, ".html$");
        my $cleanName = untaintFileName("bad \ file / name |>.ext");

REQUIRES

Perl5.005, Fcntl, File::Copy, File::stat, Time::Local, Time::localtime, Data::Handy

EXPORTS

Default: none

Optional: appendFile, catPath, copyDir, getMatchingFiles, removeTree, datedFileName, getLatestFileName, incrFile, newer, permsToString, readFile, writeFile, untaintFileName

DESCRIPTION

This is a general collection of file handling convenience functions.

FUNCTIONS

readFile

readFile(fileName, chompIt)

readFile(fileName)

Reads the named file specified and returns either a string or an array, depending on the caller. If the file could not be opened for any reason, returns undef in scalar context and an empty list () in list context. (Returning either undef or (undef) in list context is stored as a 1-element list containing undef.) Note that an empty file is then indistinguishable from an error.

Parameters:

fileName - string; name of file to read

chompIt - optional; boolean; indicates to apply chomp to each line in array context

Returns:

Contents of specified file as a string or as an array, depending upon caller's context. On failure, returns undef in scalar context and an empty list () in list context.

writeFile

writeFile(fileName, text, backupExt, binMode)

writeFile(fileName, text, backupExt)

writeFile(fileName, text)

Writes text to a file, optionally renaming the original to save as a backup. If the optional backupExt is present, then the existing file (if any) is renamed. The backupExt may be something like .bak, in which case it is appended to the file name, or something like copy_of_%s in which case the filename is plugged in to the format via sprintf. Even though typically used for text files, the behavior of text files varies from system to system. The Perl binmode function, when applied to a file, prevents any processing from being done (as in manipulating line endings for the current OS). This may be controlled via the binmode parameter.

Parameters:

fileName - string; name of file to write

text - string; text to write to file

backupExt - optional; string; file extension to use for backup file name; if omitted, file is not backed up. May be a string, in which case it is simply appended to the file name, or an sprintf format.

binMode - optional; boolean; indicates to treat file as binary or not.

Returns:

1 if successful I/O, 0 if not

appendFile

appendFile(fileName, text, overWrite, binMode)

appendFile(fileName, text, overWrite)

appendFile(fileName, text)

Appends text to a file. Even though typically used for text files, the behavior of text files varies from system to system. The Perl binmode function, when applied to a file, prevents any processing from being done (as in manipulating line endings for the current OS). This may be controlled via the binmode parameter. If the overWrite flag is true, then the file is erased before the write.

Parameters:

fileName - string; name of file to write

text - string; text to write to file

overWrite - optional; boolean; indicates to overwrite or append

binMode - optional; boolean; indicates to treat file as binary or not.

Returns:

1 if successful I/O, 0 if not

incrFile

incrFile(fileName)

Increments a counter file (with exclusive locking on non-Windows systems). That is, for a file which contains only a single number, it opens the file, increments the number, and writes it back.

Parameters:

fileName - string; name of file to increment

Returns:

1 if successful, 0 otherwise (if any part of the I/O operation sequence fails: open, lock, seek, truncate, print, or close).

newer

newer(srcfile, destfile)

Determines if a source file is newer than a destination file. Returns 1 if srcfile is newer than destfile --or-- if destfile does not exist; 0 otherwise.

Parameters:

srcfile - string; file name to check for newness

destfile - string; file name to check against

Returns:

Boolean indicating whether srcfile is newer than destfile.

catPath

catPath(dir, component)

Joins dir and component into a single file path. This is available as an alternative to File::Spec->catfile because the joining character is a virgule (/), not a system-dependent path separator. This allows the result to be used as part of a URL, if desired. (And since Perl on different systems will still recognize the virgule as a path separator.)

A further difference from File::Spec->catfile deals with boundary conditions. If dir is empty, catPath returns just component, which is a proper path assuming that an empty directory means the current directory. catfile, on the other hand, returns /component which may be a very different path than what was expected. Similarly, if component is empty, catPath returns just dir, as compared to dir/ returned by catfile.

Parameters:

dir - string; file name to check for newness

component - string; file name to check against

Returns:

Assembled path string.

datedFileName

datedFileName(fullname, fmt, year, month, day)

datedFileName(fullname, fmt)

datedFileName(fullname)

Adds a formatted date to a file name to provide a name which is unique--and sortable--by date. The date is broken down into three components--year, month, day--which are appended to the file name in that order which makes the name order monotonic for easy sorting. The name is broken into two components--the file extension, and everything else. These five components are reassembled via the standard sprintf formatting function. The format string, then, must contain 2 %s fields (for path-and-name and for extension, respectively) and 3 %d fields (for year, month, and day, respectively).

Examples:

        datedFileName("dir/stuff.txt") => dir/stuff-2001-08-11.txt
        datedFileName("stuff") => stuff-2001-08-11
        datedFileName("stuff.htm", "%s_%d%d%d.%s") => stuff_20010811.htm
Parameters:

fullname - string; full file name to update with a date

fmt - optional; sprintf format string. If omitted, "%s-%4d-%02d-%02d.%s" is used if the file has an extension, and "%s-%4d-%02d-%02d" is used if the file has no extension.

year,month,day - optional; strings specifying date to plug in to format. If omitted, current date is used.

Returns:

File name with the current date (or specified date) embedded.

copyDir

copyDir(sourceDir, targetDir, ext)

copyDir(sourceDir, targetDir)

Copies all files matching a given extension from one directory to another. If no extension is specified, copies all files. The function will report failure if any one file copy fails, though some files may have been copied. The targetDir must already exist.

Parameters:

sourceDir - string; name of directory to copy from

targetDir - string; name of directory to copy into

ext - optional; single file extension string or an array reference of same

Returns:

1 if all OK, 0 otherwise

getMatchingFiles

OBJ->getMatchingFiles(dir, regexp)

Returns list of files in the specified directory matching the specified regular expression.

Parameters:

dir - string; directory containing templates

regexp - string; file pattern to matcn

Returns:

list of file names

getLatestFileName

getLatestFileName(dirName, filePat, dateString)

getLatestFileName(dirName, filePat)

getLatestFileName(dirName)

Returns the name of the file in the specified directory, matching the regular expression filePat, which has the latest modification date (i.e. the most recent). The search may be further restricted to find the latest file relative to any date, not just the current date, via the optional dateString parameter.

Parameters:

dirName - string; name of directory to search

filePat - optional; regexp string used to filter directory. If omitted, finds the most recent file in the entire directory.

dateString - optional; string in the format of yyyy/mm/dd, used to restrict results to latest match but no later than this date. If omitted, finds the most recent file relative to the current date.

Returns:

file name meeting constraints or undef if none found

permsToString

permsToString(stat)

permsToString(filename)

Returns the permissions of the specified file as a human-readable string, in the same format as a unix/linux "ls -l" command. Thus, full permissions would be represented by "rwxrwxrwx", while full owner access, but read-only for others would be "rwxr--r--". Currently does not handle directories, setuid, or setgid representation.

Parameters:

stat - File::stat object

filename - string representing file name

Returns:

string representing permissions of target file

removeTree

removeTree(path)

Removes a directory and everything in it. Adapted from http://forge.novell.com/modules/xfref_library/detail.php?reference_id=234

Parameters:

path - root of tree to delete

Returns:

count of files and directories deleted, or undef if problem

untaintFileName

untaintFileName(string)

This method filters out characters that might cause problems in a filename, such as a path separator character (/ or \). The full set of allowed characters is: "0-9a-zA-Z.,_&+~#()-" . Any disallowed characters are replaced with a space, then any multiple spaces are reduced to a single space. An empty or undefined input will return the string "BLANK". Finally, the returned string is truncated at 64 characters if it exceeds that length.

Parameters:

fileName - name of file to untaint

Returns:

Untainted file name

BUGS

None

AUTHOR

Michael Sorens

VERSION

$Revision: 8 $ $Date: 2006-12-19 21:13:43 -0800 (Tue, 19 Dec 2006) $

SINCE

CleanCode 0.9

SEE ALSO

perl(1)

POD ERRORS

Hey! The above document had some coding errors, which are explained below:

Around line 734:

=back doesn't take any parameters, but you said =back -- end of FUNCTION section


CleanCode Perl Libraries Copyright © 2001-2013 Michael Sorens - Revised 2013.06.30 Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads