This is Info file pm.info, produced by Makeinfo version 1.68 from the input file bigpm.texi.  File: pm.info, Node: File/Remove, Next: File/Slurp, Prev: File/Remote, Up: Module List Remove files and directories **************************** NAME ==== *File::Remove* - Remove files and directories SYNOPSIS ======== use File::Remove qw(remove); remove \1,"file1","file2","directory1","file3","directory2","file4", "directory2","file5","directory3"; # removes only files, even if the filespec matches a directory remove "*.c","*.pl"; # recurses into subdirectories and removes them all remove \1, "directory"; DESCRIPTION =========== *File::Remove::remove* removes files and directories. It acts like rm for the most part. Although unlink can be given a list of files it will not remove directories. This module remedies that. It also accepts wildcards, * and ?, as arguments for filenames. remove Removes files and directories. Directories are removed recursively like in *rm -rf* if the first argument is a reference to a scalar that evaluates to true. If the first arguemnt is a reference to a scalar then it is used as the value of the recursive flag. By default it's false so only pass \1 to it. In list context it returns a list of files/directories removed, in scalar context it returns the number of files/directories removed. The list/number should match what was passed in if everything went well. rm Just calls remove. It's there for people who get tired of typing 'remove'. EXAMPLE ======= See SYNOPSIS. BUGS ==== Not that I know of. ;) AUTHOR ====== Gabor Egressy *gabor@vmunix.com* Copyright (c) 1998 Gabor Egressy. All rights reserved. All wrongs reversed. This program is free software; you can redistribute and/or modify it under the same terms as Perl itself.  File: pm.info, Node: File/Slurp, Next: File/Sort, Prev: File/Remove, Up: Module List single call read & write file routines; read directories ******************************************************** NAME ==== File::Slurp -- single call read & write file routines; read directories SYNOPSIS ======== use File::Slurp; $all_of_it = read_file($filename); @all_lines = read_file($filename); write_file($filename, @contents) overwrite_file($filename, @new_contnts); append_file($filename, @additional_contents); @files = read_dir($directory); DESCRIPTION =========== These are quickie routines that are meant to save a couple of lines of code over and over again. They do not do anything fancy. read_file() does what you would expect. If you are using its output in array context, then it returns an array of lines. If you are calling it from scalar context, then returns the entire file in a single string. It croaks()s if it can't open the file. write_file() creates or overwrites files. append_file() appends to a file. overwrite_file() does an in-place update of an existing file or creates a new file if it didn't already exist. Write_file will also replace a file. The difference is that the first that that write_file() does is to trucate the file whereas the last thing that overwrite_file() is to trucate the file. Overwrite_file() should be used in situations where you have a file that always needs to have contents, even in the middle of an update. read_dir() returns all of the entries in a directory except for "." and "..". It croaks if it cannot open the directory. AUTHOR ====== David Muir Sharnoff  File: pm.info, Node: File/Sort, Next: File/Spec, Prev: File/Slurp, Up: Module List Sort a file or merge sort multiple files **************************************** NAME ==== File::Sort - Sort a file or merge sort multiple files SYNOPSIS ======== use File::Sort qw(sort_file); sort_file({ I => [qw(file_1 file_2)], o => 'file_new', k => '5.3,5.5rn', -t => '|' }); sort_file('file1', 'file1.sorted'); DESCRIPTION =========== ***DANGER, WILL ROBINSON*** The interface has changed in some significant ways from 0.1x. See `"HISTORY"' in this node. This module sorts text files by lines (or records). Comparisons are based on one or more sort keys extracted from each line of input, and are performed lexicographically. By default, if keys are not given, sort regards each input line as a single field. The sort is a merge sort. If you don't like that, feel free to change it. Options ------- The following options are available, and are passed in the hash reference passed to the function in the format: OPTION => VALUE Where an option can take multiple values (like I, k, and pos), values may be passed via an anonymous array: OPTION => [VALUE1, VALUE2] Where the OPTION is a switch, it should be passed a boolean VALUE of 1 or 0. This interface will always be supported, though a more perlish interface may be offered in the future, as well. This interface is basically a mapping of the command-line options to the Unix sort utility. I INPUT Pass in the input file(s). This can be either a single string with the filename, or an array reference containing multiple filename strings. c Check that single input fle is ordered as specified by the arguments and the collating sequence of the current locale. No output is produced; only the exit code is affected. m Merge only; the input files are assumed to already be sorted. o OUTPUT Specify the name of an OUTPUT file to be used instead of the standard output. u Unique: Suppresses all but one in each set of lines having equal keys. If used with the c option check that there are no lines with consecutive lines with duplicate keys, in addition to checking that the input file is sorted. y MAX_SORT_RECORDS Maximum number of lines (records) read before writing to temp file. Default is 200,000. This may eventually change to be kbytes instead of lines. Lines was easier to implement. Can also specify with MAX_SORT_RECORDS environment variable. F MAX_SORT_FILES Maximum number of temp files to be held open at once. Default to 40, as older Windows ports had quite a small limit. Can also specify with MAX_SORT_FILES environment variable. No temp files will be used at all if MAX_SORT_RECORDS is never reached. D Send debugging information to STDERR. Behavior subject to change. The following options override the default ordering rules. When ordering options appear independent of any key field specifications, the requested field ordering rules are applied globally to all sort keys. When attached to a specific key (see k), the specified ordering options override all global ordering options for that key. d Specify that only blank characters and alphanumeric characters, according to the current locale setting, are significant in comparisons. d overrides i. f Consider all lower-case characters that have upper-case equivalents, according to the current locale setting, to be the upper-case equivalent for the purposes of comparison. i Ignores all characters that are non-printable, according to the current locale setting. n Does numeric instead of string compare, using whatever perl considers to be a number in numeric comparisons. r Reverse the sense of the comparisons. b Ignore leading blank characters when determining the starting and ending positions of a restricted sort key. If the b option is specified before the first k option, it is applied to all k options. Otherwise, the b option can be attached indepently to each field_start or field_end option argument (see below). t STRING Use STRING as the field separator character; char is not considered to be part of a field (although it can be included in a sort key). Each occurrence of char is significant (for example, delimits an empty field). If t is not specified, blank characters are used as default field separators; each maximal non-empty sequence of blank characters that follows a non-blank character is a field separator. X STRING Same as t, but STRING is interpreted as a Perl regular expression instead. Do not escape any characters (/ characters need to be escaped internally, and will be escaped for you). The string matched by STRING is not included in the fields themselves, unless demanded by perl's regex and split semantics (e.g., regexes in parentheses will add that matched expression as an extra field). See *Note Perlre: (perl.info)perlre, and `split', *Note Perlfunc: (perl.info)perlfunc,. R STRING Record separator, defaults to newline. k *pos1[,pos2]* The keydef argument is a restricted sort key field definition. The format of this definition is: field_start[.first_char][type][,field_end[.last_char][type]] where field_start and field_end define a key field restricted to a portion of the line, and type is a modifier from the list of characters b, d, f, i, n, r. The b modifier behaves like the b option, but applies only to the field_start or field_end to which it is attached. The other modifiers behave like the corresponding options, but apply only to the key field to which they are attached; they have this effect if specified with field_start, field_end, or both. If any modifier is attached to a field_start or a field_end, no option applies to either. Occurrences of the k option are significant in command line order. If no k option is specified, a default sort key of the entire line is used. When there are multiple keys fields, later keys are compared only after all earlier keys compare equal. Except when the u option is specified, lines that otherwise compare equal are ordered as if none of the options d, f, i, n or k were present (but with r still in effect, if it was specified) and with all bytes in the lines significant to the comparison. The order in which lines that still compare equal are written is unspecified. pos *+pos1 [-pos2]* Similar to k, these are mostly obsolete switches, but some people like them and want to use them. Usage is: +field_start[.first_char][type] [-field_end[.last_char][type]] Where field_end in k specified the last position to be included, it specifes the last position to NOT be included. Also, numbers are counted from 0 instead of 1. *pos2* must immediately follow corresponding *+pos1*. The rest should be the same as the k option. Mixing *+pos1* *pos2* with k is allowed, but will result in all of the *+pos1* *pos2* options being ordered AFTER the k options. It is best if you Don't Do That. Pick one and stick with it. Here are some equivalencies: pos => '+1 -2' -> k => '2,2' pos => '+1.1 -1.2' -> k => '2.2,2.2' pos => ['+1 -2', '+3 -5'] -> k => ['2,2', '4,5'] pos => ['+2', '+0b -1'] -> k => ['3', '1b,1'] pos => '+2.1 -2.4' -> k => '3.2,3.4' pos => '+2.0 -3.0' -> k => '3.1,4.0' Not Implemented --------------- If the options are not listed as implemented above, or are not listed in TODO below, they are not in the plan for implementation. This includes T and z. EXAMPLES ======== Sort file by straight string compare of each line, sending output to STDOUT. use File::Sort qw(sort_file); sort_file('file'); Sort contents of file by second key in file. sort_file({k => 2, I => 'file'}); Sort, in reverse order, contents of file1 and file2, placing output in outfile and using second character of second field as the sort key. sort_file({ r => 1, k => '2.2,2.2', o => 'outfile', I => ['file1', 'file2'] }); Same sort but sorting numerically on characters 3 through 5 of the fifth field first, and only return records with unique keys. sort_file({ u => 1, r => 1, k => ['5.3,5.5rn', '2.2,2.2'], o => 'outfile', I => ['file1', 'file2'] }); Print passwd(4) file sorted by numeric user ID. sort_file({t => ':', k => '3n', I => '/etc/passwd'}); For the anal sysadmin, check that passwd(4) file is sorted by numeric user ID. sort_file({c => 1, t => ':', k => '3n', I => '/etc/passwd'}); ENVIRONMENT =========== MAX_SORT_RECORDS Default is 200,000. Maximum number of records to use before writing to a temp file. Overriden by y option. MAX_SORT_FILES Maximum number of open temp files to use before merging open temp files. Overriden by F option. LC_COLLATE Determine the locale for ordering rules. LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single- versus multi-byte characters in arguments and input files) and the behaviour of character classification for the b, d, f, i and n options. EXPORT ====== Exports `sort_file' on request. TODO ==== Better debugging and error reporting Performance hit with -u Do bytes instead of lines Tests fail on non-ASCII locales. HISTORY ======= v0.91, Saturday, February 12, 2000 Closed all files in test.pl so they could be unlinked on some platforms. (Hubert Toullec) Documented I option. (Hubert Toullec) Removed O_EXCL flag from `sort_file'. Fixed bug in sorting multiple files. (Paul Eckert) v0.90, Friday, April 30, 1999 Complete rewrite. Took the code from this module to write sort utility for PPT project, then brought changes back over. As a result the interface has changed slightly, mostly in regard to what letters are used for options, but there are also some key behavioral differences. If you need the old interface, the old module will remain on CPAN, but will not be supported. Sorry for any inconvenience this may cause. The good news is that it should not be too difficult to update your code to use the new interface. v0.20 Fixed bug with unique option (didn't work :). Switched to sysopen for better portability. Print to STDOUT if no output file supplied. Added c option to check sorting. v0.18 (31 January 1998) Tests 3 and 4 failed because we hit the open file limit in the standard Windows port of perl5.004_02 (50). Adjusted the default for total number of temp files from 50 to 40 (leave room for other open files), changed docs. (Mike Blazer, Gurusamy Sarathy) v0.17 (30 December 1998) Fixed bug in `_merge_files' that tried to open a passed IO::File object. Fixed up docs and did some more tests and benchmarks. v0.16 (24 December 1998) One year between releases was too long. I made changes Miko O'Sullivan wanted, and I didn't even know I had made them. Also now use IO::File to create temp files, so the TMPDIR option is no longer supported. Hopefully made the whole thing more robust and faster, while supporting more options for sorting, including delimited sorts, and arbitrary sorts. Made CHUNK default a lot larger, which improves performance. On low-memory systems, or where (e.g.) the MacPerl binary is not allocated much RAM, it might need to be lowered. v0.11 (04 January 1998) More cleanup; fixed special case of no linebreak on last line; wrote test suite; fixed warning for redefined subs (sort1 and sort2). v0.10 (03 January 1998) Some cleanup; made it not subject to system file limitations; separated many parts out into separate functions. v0.03 (23 December 1997) Added reverse and numeric sorting options. v0.02 (19 December 1997) Added unique and merge-only options. v0.01 (18 December 1997) First release. THANKS ====== Mike Blazer , Vicki Brown , Tom Christiansen , Albert Dvornik , Paul Eckert , Gene Hsu , Andrew M. Langmead , Brian L. Matthews , Rich Morin , Matthias Neeracher , Miko O'Sullivan , Tom Phoneix , Gurusamy Sarathy Hubert Toullec . AUTHOR ====== Chris Nandor , http://pudge.net/ Copyright (c) 2000 Chris Nandor. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the Artistic License, distributed with Perl. VERSION ======= v0.91, Saturday, February 12, 2000 SEE ALSO ======== sort(1), locale, PPT project, .  File: pm.info, Node: File/Spec, Next: File/Spec/Functions, Prev: File/Sort, Up: Module List portably perform operations on file names ***************************************** NAME ==== File::Spec - portably perform operations on file names SYNOPSIS ======== use File::Spec; $x=File::Spec->catfile('a', 'b', 'c'); which returns 'a/b/c' under Unix. Or: use File::Spec::Functions; $x = catfile('a', 'b', 'c'); DESCRIPTION =========== This module is designed to support operations commonly performed on file specifications (usually called "file names", but not to be confused with the contents of a file, or Perl's file handles), such as concatenating several directory and file names into a single path, or determining whether a path is rooted. It is based on code directly taken from MakeMaker 5.17, code written by Andreas KEnig, Andy Dougherty, Charles Bailey, Ilya Zakharevich, Paul Schinder, and others. Since these functions are different for most operating systems, each set of OS specific routines is available in a separate module, including: File::Spec::Unix File::Spec::Mac File::Spec::OS2 File::Spec::Win32 File::Spec::VMS The module appropriate for the current OS is automatically loaded by File::Spec. Since some modules (like VMS) make use of facilities available only under that OS, it may not be possible to load all modules under all operating systems. Since File::Spec is object oriented, subroutines should not called directly, as in: File::Spec::catfile('a','b'); but rather as class methods: File::Spec->catfile('a','b'); For simple uses, *Note File/Spec/Functions: File/Spec/Functions, provides convenient functional forms of these methods. For a list of available methods, please consult *Note File/Spec/Unix: File/Spec/Unix,, which contains the entire set, and which is inherited by the modules for other platforms. For further information, please see *Note File/Spec/Mac: File/Spec/Mac,, *Note File/Spec/OS2: File/Spec/OS2,, *Note File/Spec/Win32: File/Spec/Win32,, or *Note File/Spec/VMS: File/Spec/VMS,. SEE ALSO ======== File::Spec::Unix, File::Spec::Mac, File::Spec::OS2, File::Spec::Win32, File::Spec::VMS, File::Spec::Functions, ExtUtils::MakeMaker AUTHORS ======= Kenneth Albanowski <`kjahds@kjahds.com'>, Andy Dougherty <`doughera@lafcol.lafayette.edu'>, Andreas KEnig <`A.Koenig@franz.ww.TU-Berlin.DE'>, Tim Bunce <`Tim.Bunce@ig.co.uk'>. VMS support by Charles Bailey <`bailey@newman.upenn.edu'>. OS/2 support by Ilya Zakharevich <`ilya@math.ohio-state.edu'>. Mac support by Paul Schinder <`schinder@pobox.com'>. abs2rel() and rel2abs() written by Shigio Yamaguchi <`shigio@tamacom.com'>, modified by Barrie Slaymaker <`barries@slaysys.com'>. splitpath(), splitdir(), catpath() and catdir() by Barrie Slaymaker.  File: pm.info, Node: File/Spec/Functions, Next: File/Spec/Mac, Prev: File/Spec, Up: Module List portably perform operations on file names ***************************************** NAME ==== File::Spec::Functions - portably perform operations on file names SYNOPSIS ======== use File::Spec::Functions; $x = catfile('a','b'); DESCRIPTION =========== This module exports convenience functions for all of the class methods provided by File::Spec. For a reference of available functions, please consult *Note File/Spec/Unix: File/Spec/Unix,, which contains the entire set, and which is inherited by the modules for other platforms. For further information, please see *Note File/Spec/Mac: File/Spec/Mac,, *Note File/Spec/OS2: File/Spec/OS2,, *Note File/Spec/Win32: File/Spec/Win32,, or *Note File/Spec/VMS: File/Spec/VMS,. Exports ------- The following functions are exported by default. canonpath catdir catfile curdir rootdir updir no_upwards file_name_is_absolute path The following functions are exported only by request. devnull tmpdir splitpath splitdir catpath abs2rel rel2abs All the functions may be imported using the :ALL tag. SEE ALSO ======== File::Spec, File::Spec::Unix, File::Spec::Mac, File::Spec::OS2, File::Spec::Win32, File::Spec::VMS, ExtUtils::MakeMaker  File: pm.info, Node: File/Spec/Mac, Next: File/Spec/OS2, Prev: File/Spec/Functions, Up: Module List File::Spec for MacOS ******************** NAME ==== File::Spec::Mac - File::Spec for MacOS SYNOPSIS ======== require File::Spec::Mac; # Done internally by File::Spec if needed DESCRIPTION =========== Methods for manipulating file specifications. METHODS ======= canonpath On MacOS, there's nothing to be done. Returns what it's given. catdir Concatenate two or more directory names to form a complete path ending with a directory. Put a trailing : on the end of the complete path if there isn't one, because that's what's done in MacPerl's environment. The fundamental requirement of this routine is that File::Spec->catdir(split(":",$path)) eq $path But because of the nature of Macintosh paths, some additional possibilities are allowed to make using this routine give reasonable results for some common situations. Here are the rules that are used. Each argument has its trailing ":" removed. Each argument, except the first, has its leading ":" removed. They are then joined together by a ":". So File::Spec->catdir("a","b") = "a:b:" File::Spec->catdir("a:",":b") = "a:b:" File::Spec->catdir("a:","b") = "a:b:" File::Spec->catdir("a",":b") = "a:b" File::Spec->catdir("a","","b") = "a::b" etc. To get a relative path (one beginning with :), begin the first argument with : or put a "" as the first argument. If you don't want to worry about these rules, never allow a ":" on the ends of any of the arguments except at the beginning of the first. Under MacPerl, there is an additional ambiguity. Does the user intend that File::Spec->catfile("LWP","Protocol","http.pm") be relative or absolute? There's no way of telling except by checking for the existence of LWP: or :LWP, and even there he may mean a dismounted volume or a relative path in a different directory (like in @INC). So those checks aren't done here. This routine will treat this as absolute. catfile Concatenate one or more directory names and a filename to form a complete path ending with a filename. Since this uses catdir, the same caveats apply. Note that the leading : is removed from the filename, so that File::Spec->catfile($ENV{HOME},"file"); and File::Spec->catfile($ENV{HOME},":file"); give the same answer, as one might expect. curdir Returns a string representing the current directory. devnull Returns a string representing the null device. rootdir Returns a string representing the root directory. Under MacPerl, returns the name of the startup volume, since that's the closest in concept, although other volumes aren't rooted there. tmpdir Returns a string representation of the first existing directory from the following list or " if none exist: $ENV{TMPDIR} updir Returns a string representing the parent directory. file_name_is_absolute Takes as argument a path and returns true, if it is an absolute path. In the case where a name can be either relative or absolute (for example, a folder named "HD" in the current working directory on a drive named "HD"), relative wins. Use ":" in the appropriate place in the path if you want to distinguish unambiguously. As a special case, the file name " is always considered to be absolute. path Returns the null list for the MacPerl application, since the concept is usually meaningless under MacOS. But if you're using the MacPerl tool under MPW, it gives back $ENV{Commands} suitably split, as is done in :lib:ExtUtils:MM_Mac.pm. splitpath splitdir catpath abs2rel See `abs2rel', *Note File/Spec/Unix: File/Spec/Unix, for general documentation. Unlike `File::Spec::Unix-'abs2rel()>, this function will make checks against the local filesystem if necessary. See `' in this node for details. rel2abs See `rel2abs', *Note File/Spec/Unix: File/Spec/Unix, for general documentation. Unlike `File::Spec::Unix-'rel2abs()>, this function will make checks against the local filesystem if necessary. See `' in this node for details. SEE ALSO ======== *Note File/Spec: File/Spec,  File: pm.info, Node: File/Spec/OS2, Next: File/Spec/Unix, Prev: File/Spec/Mac, Up: Module List methods for OS/2 file specs *************************** NAME ==== File::Spec::OS2 - methods for OS/2 file specs SYNOPSIS ======== require File::Spec::OS2; # Done internally by File::Spec if needed DESCRIPTION =========== See File::Spec::Unix for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics.  File: pm.info, Node: File/Spec/Unix, Next: File/Spec/VMS, Prev: File/Spec/OS2, Up: Module List methods used by File::Spec ************************** NAME ==== File::Spec::Unix - methods used by File::Spec SYNOPSIS ======== require File::Spec::Unix; # Done automatically by File::Spec DESCRIPTION =========== Methods for manipulating file specifications. METHODS ======= canonpath No physical check on the filesystem, but a logical cleanup of a path. On UNIX eliminated successive slashes and successive "/.". $cpath = File::Spec->canonpath( $path ) ; catdir Concatenate two or more directory names to form a complete path ending with a directory. But remove the trailing slash from the resulting string, because it doesn't look good, isn't necessary and confuses OS2. Of course, if this is the root directory, don't cut off the trailing slash :-) catfile Concatenate one or more directory names and a filename to form a complete path ending with a filename curdir Returns a string representation of the current directory. "." on UNIX. devnull Returns a string representation of the null device. "/dev/null" on UNIX. rootdir Returns a string representation of the root directory. "/" on UNIX. tmpdir Returns a string representation of the first writable directory from the following list or "" if none are writable: $ENV{TMPDIR} /tmp updir Returns a string representation of the parent directory. ".." on UNIX. no_upwards Given a list of file names, strip out those that refer to a parent directory. (Does not strip symlinks, only '.', '..', and equivalents.) case_tolerant Returns a true or false value indicating, respectively, that alphabetic is not or is significant when comparing file specifications. file_name_is_absolute Takes as argument a path and returns true if it is an absolute path. This does not consult the local filesystem on Unix, Win32, or OS/2. It does sometimes on MacOS (see `File::Spec::MacOS' in this node). It does consult the working environment for VMS (see `file_name_is_absolute', *Note File/Spec/VMS: File/Spec/VMS,). path Takes no argument, returns the environment variable PATH as an array. join join is the same as catfile. splitpath ($volume,$directories,$file) = File::Spec->splitpath( $path ); ($volume,$directories,$file) = File::Spec->splitpath( $path, $no_file ); Splits a path in to volume, directory, and filename portions. On systems with no concept of volume, returns undef for volume. For systems with no syntax differentiating filenames from directories, assumes that the last file is a path unless $no_file is true or a trailing separator or /. or /.. is present. On Unix this means that $no_file true makes this return ( ", $path, " ). The directory portion may or may not be returned with a trailing '/'. The results can be passed to `' in this node to get back a path equivalent to (usually identical to) the original path. splitdir The opposite of `' in this node. @dirs = File::Spec->splitdir( $directories ); $directories must be only the directory portion of the path on systems that have the concept of a volume or that have path syntax that differentiates files from directories. Unlike just splitting the directories on the separator, empty directory names (") can be returned, because these are significant on some OSs (e.g. MacOS). On Unix, File::Spec->splitdir( "/a/b//c/" ); Yields: ( '', 'a', 'b', '', 'c', '' ) catpath Takes volume, directory and file portions and returns an entire path. Under Unix, $volume is ignored, and directory and file are catenated. A '/' is inserted if need be. On other OSs, $volume is significant. abs2rel Takes a destination path and an optional base path returns a relative path from the base path to the destination path: $rel_path = File::Spec->abs2rel( $path ) ; $rel_path = File::Spec->abs2rel( $path, $base ) ; If $base is not present or ", then `cwd()' in this node is used. If $base is relative, then it is converted to absolute form using `' in this node. This means that it is taken to be relative to `cwd()' in this node. On systems with the concept of a volume, this assumes that both paths are on the $destination volume, and ignores the $base volume. On systems that have a grammar that indicates filenames, this ignores the $base filename as well. Otherwise all path components are assumed to be directories. If $path is relative, it is converted to absolute form using `' in this node. This means that it is taken to be relative to `cwd()' in this node. No checks against the filesystem are made on most systems. On MacOS, the filesystem may be consulted (see `File::Spec::MacOS' in this node). On VMS, there is interaction with the working environment, as logicals and macros are expanded. Based on code written by Shigio Yamaguchi. rel2abs Converts a relative path to an absolute path. $abs_path = File::Spec->rel2abs( $path ) ; $abs_path = File::Spec->rel2abs( $path, $base ) ; If $base is not present or ", then `cwd()' in this node is used. If $base is relative, then it is converted to absolute form using `' in this node. This means that it is taken to be relative to `cwd()' in this node. On systems with the concept of a volume, this assumes that both paths are on the $base volume, and ignores the $path volume. On systems that have a grammar that indicates filenames, this ignores the $base filename as well. Otherwise all path components are assumed to be directories. If $path is absolute, it is cleaned up and returned using `' in this node. No checks against the filesystem are made on most systems. On MacOS, the filesystem may be consulted (see `File::Spec::MacOS' in this node). On VMS, there is interaction with the working environment, as logicals and macros are expanded. Based on code written by Shigio Yamaguchi. SEE ALSO ======== *Note File/Spec: File/Spec,  File: pm.info, Node: File/Spec/VMS, Next: File/Spec/Win32, Prev: File/Spec/Unix, Up: Module List methods for VMS file specs ************************** NAME ==== File::Spec::VMS - methods for VMS file specs SYNOPSIS ======== require File::Spec::VMS; # Done internally by File::Spec if needed DESCRIPTION =========== See File::Spec::Unix for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics. eliminate_macros Expands MM[KS]/Make macros in a text string, using the contents of identically named elements of `%$self', and returns the result as a file specification in Unix syntax. fixpath Catchall routine to clean up problem MM[SK]/Make macros. Expands macros in any directory specification, in order to avoid juxtaposing two VMS-syntax directories when MM[SK] is run. Also expands expressions which are all macro, so that we can tell how long the expansion is, and avoid overrunning DCL's command buffer when MM[KS] is running. If optional second argument has a TRUE value, then the return string is a VMS-syntax directory specification, if it is FALSE, the return string is a VMS-syntax file specification, and if it is not specified, fixpath() checks to see whether it matches the name of a directory in the current default directory, and returns a directory or file specification accordingly. Methods always loaded --------------------- canonpath (override) Removes redundant portions of file specifications according to VMS syntax. catdir Concatenates a list of file specifications, and returns the result as a VMS-syntax directory specification. No check is made for "impossible" cases (e.g. elements other than the first being absolute filespecs). catfile Concatenates a list of file specifications, and returns the result as a VMS-syntax file specification. curdir (override) Returns a string representation of the current directory: '[]' devnull (override) Returns a string representation of the null device: '_NLA0:' rootdir (override) Returns a string representation of the root directory: 'SYS$DISK:[000000]' tmpdir (override) Returns a string representation of the first writable directory from the following list or " if none are writable: sys$scratch $ENV{TMPDIR} updir (override) Returns a string representation of the parent directory: '[-]' case_tolerant (override) VMS file specification syntax is case-tolerant. path (override) Translate logical name DCL$PATH as a searchlist, rather than trying to split string value of `$ENV{'PATH'}'. file_name_is_absolute (override) Checks for VMS directory spec as well as Unix separators. splitpath (override) Splits using VMS syntax. splitdir (override) Split dirspec using VMS syntax. catpath (override) Construct a complete filespec using VMS syntax abs2rel (override) Use VMS syntax when converting filespecs. rel2abs (override) Use VMS syntax when converting filespecs. SEE ALSO ======== *Note File/Spec: File/Spec,  File: pm.info, Node: File/Spec/Win32, Next: File/Sync, Prev: File/Spec/VMS, Up: Module List methods for Win32 file specs **************************** NAME ==== File::Spec::Win32 - methods for Win32 file specs SYNOPSIS ======== require File::Spec::Win32; # Done internally by File::Spec if needed DESCRIPTION =========== See File::Spec::Unix for a documentation of the methods provided there. This package overrides the implementation of these methods, not the semantics. devnull Returns a string representation of the null device. tmpdir Returns a string representation of the first existing directory from the following list: $ENV{TMPDIR} $ENV{TEMP} $ENV{TMP} /tmp / catfile Concatenate one or more directory names and a filename to form a complete path ending with a filename canonpath No physical check on the filesystem, but a logical cleanup of a path. On UNIX eliminated successive slashes and successive "/.". splitpath ($volume,$directories,$file) = File::Spec->splitpath( $path ); ($volume,$directories,$file) = File::Spec->splitpath( $path, $no_file ); Splits a path in to volume, directory, and filename portions. Assumes that the last file is a path unless the path ends in '\\', '\\.', '\\..' or $no_file is true. On Win32 this means that $no_file true makes this return ( $volume, $path, undef ). Separators accepted are \ and /. Volumes can be drive letters or UNC sharenames (\\server\share). The results can be passed to `' in this node to get back a path equivalent to (usually identical to) the original path. splitdir The opposite of `' in this node. @dirs = File::Spec->splitdir( $directories ); $directories must be only the directory portion of the path on systems that have the concept of a volume or that have path syntax that differentiates files from directories. Unlike just splitting the directories on the separator, leading empty and trailing directory entries can be returned, because these are significant on some OSs. So, File::Spec->splitdir( "/a/b/c" ); Yields: ( '', 'a', 'b', '', 'c', '' ) catpath Takes volume, directory and file portions and returns an entire path. Under Unix, $volume is ignored, and this is just like catfile(). On other OSs, the $volume become significant. SEE ALSO ======== *Note File/Spec: File/Spec,  File: pm.info, Node: File/Sync, Next: File/Tail, Prev: File/Spec/Win32, Up: Module List Perl access to fsync() and sync() function calls ************************************************ NAME ==== File::Sync - Perl access to fsync() and sync() function calls SYNOPSIS ======== use File::Sync qw(fsync sync); fsync(\*FILEHANDLE) or die "fsync: $!"; sync(); use File::Sync qw(fsync); use IO::File; $fh = IO::File->new("> /tmp/foo") or die "new IO::File: $!"; ... fsync($fh) or die "fsync: $!"; DESCRIPTION =========== The fsync() function takes a Perl file handle as its only argument, and passes its fileno() to the C function fsync(). It returns undef on failure, or *true* on success. The fsync_fd() function is used internally by fsync(); it takes a file descriptor as its only argument. The sync() function is identical to the C function sync(). This module does not export any methods by default, but fsync() is made available as a method of the FileHandle and IO::Handle classes. NOTES ===== Doing fsync() if the stdio buffers aren't flushed (with $| or the autoflush method) is probably pointless. Calling sync() too often on a multi-user system is slightly antisocial. AUTHOR ====== Carey Evans <*c.evans@clear.net.nz*> SEE ALSO ======== perl(1), fsync(2), sync(2), perlvar(1)  File: pm.info, Node: File/Tail, Next: File/Temp, Prev: File/Sync, Up: Module List Perl extension for reading from continously updated files ********************************************************* NAME ==== File::Tail - Perl extension for reading from continously updated files SYNOPSIS ======== use File::Tail; $file=File::Tail->new("/some/log/file"); while (defined($line=$file->read)) { print "$line"; } use File::Tail; $file=File::Tail->new(name=>$name, maxinterval=>300, adjustafter=>7); while (defined($line=$file->read)) { print "$line"; } OR, you could use tie (additional parameters can be passed with the name, or can be set using $ref): use File::Tail; my $ref=tie *FH,"File::Tail",(name=>$name); while () { print "$_"; } } Note that the above script will never exit. If there is nothing being written to the file, it will simply block. You can find more synopsii in the file logwatch, which is included in the distribution. Note: Select functionality was added in version 0.9, and it required some reworking of all routines. ***PLEASE*** let me know if you see anything strange happening. You can find two way of using select in the file select_demo which is included in the ditribution. DESCRIPTION =========== The primary purpose of File::Tail is reading and analysing log files while they are being written, which is especialy usefull if you are monitoring the logging process with a tool like Tobias Oetiker's MRTG. The module tries very hard NOT to "busy-wait" on a file that has little traffic. Any time it reads new data from the file, it counts the number of new lines, and divides that number by the time that passed since data were last written to the file before that. That is considered the average time before new data will be written. When there is no new data to read, `File::Tail' sleeps for that number of seconds. Thereafter, the waiting time is recomputed dynamicaly. Note that `File::Tail' never sleeps for more than the number of seconds set by maxinterval. If the file does not get altered for a while, `File::Tail' gets suspicious and startschecking if the file was truncated, or moved and recreated. If anything like that had happened, `File::Tail' will quietly reopen the file, and continue reading. The only way to affect what happens on reopen is by setting the reset_tail parameter (see below). The effect of this is that the scripts need not be aware when the logfiles were rotated, they will just quietly work on. Note that the sleep and time used are from Time::HiRes, so this module should do the right thing even if the time to sleep is less than one second. The logwatch script (also included) demonstrates several ways of calling the methods. CONSTRUCTOR =========== new ([ ARGS ]) -------------- Creates a `File::Tail'. If it has only one paramter, it is assumed to be the filename. If the open fails, the module performs a croak. I am currently looking for a way to set $! and return undef. You can pass several parameters to new: name This is the name of the file to open. The file will be opened for reading. This must be a regular file, not a pipe or a terminal (i.e. it must be seekable). maxinterval The maximum number of seconds (real number) that will be spent sleeping. Default is 60, meaning `File::Tail' will never spend more than sixty seconds without checking the file. interval The initial number of seconds (real number) that will be spent sleeping, before the file is first checked. Default is ten seconds, meaning `File::Tail' will sleep for 10 seconds and then determine, how many new lines have appeared in the file. adjustafter The number of times `File::Tail' waits for the current interval, before adjusting the interval upwards. The default is 10. resetafter The number of seconds after last change when `File::Tail' decides the file may have been closed and reopened. The default is adjustafter*maxinterval. maxbuf The maximum size of the internal buffer. When File::Tail suddenly found an enormous ammount of information in the file (for instance if the retry parameters were set to very infrequent checking and the file was rotated), File::Tail sometimes slurped way too much file into memory. This sets the maximum size of File::Tail's buffer. Default value is 16384 (bytes). A large internal buffer may result in worse performance (as well as increased memory usage), since File::Tail will have to do more work processing the internal buffer. nowait Does not block on read, but returns an empty string if there is nothing to read. DO NOT USE THIS unless you know what you are doing. If you are using it in a loop, you probably DON'T know what you are doing. If you want to read tails from multiple files, use select. ignore_nonexistant Do not complain if the file doesn't exist when it is first opened or when it is to be reopened. (File may be reopened after resetafter seconds have passed since last data was found.) tail When first started, read and return C lines from the file. If C is zero, start at the end of file. If C is negative, return the whole file. Default is C<0>. reset_tail Same as tail, but applies after reset. (i.e. after the file has been automaticaly closed and reopened). Defaults to C<-1>, i.e. does not skip any information present in the file when it first checks it. Why would you want it otherwise? I've seen files which have been cycled like this: grep -v lastmonth log >newlog mv log archive/lastmonth mv newlog log kill -HUP logger Obviously, if this happens and you have reset_tail set to c<-1>, you will suddenly get a whole bunch of lines - lines you already saw. So in this case, reset_tail should probably be set to a small positive number or even 0. debug Set to nonzero if you want to see more about the inner workings of File::Tail. Otherwise not useful. errmode Modeled after the methods from Net:Telnet, here you decide how the errors should be handled. The parameter can be a code reference which is called with the error string as a parameter, an array with a code reference as the first parameter and other parameters to be passed to handler subroutine, or one of the words: return - ignore any error (just put error message in errmsg). warn - output the error message but continue die - display error message and exit Default is die. METHODS ======= read ---- read returns one line from the input file. If there are no lines ready, it blocks until there are. select ------ select is intended to enable the programmer to simoultaneously wait for input on normal filehandles and File::Tail filehandles. Of course, you may use it to simply read from more than one File::Tail filehandle at a time. For an example of usage, look at the script select_demo. Basicaly, you call File::Tail::select just as you would normal select, with fields for rbits, wbits and ebits, as well as a timeout, however, you can tack any number of File::Tail objects (not File::Tail filehandles!) to the end. When you do this, File::Tail's select emulates normal select, with two exceptions: a) it will return if there is input on any of the parameters (i.e. normal filehandles) _or_ File::Tails. b) In addition to `($nfound, $timeleft)', the return array will also contain a list of File::Tail objects which are ready for reading. `$nfound' will contain the correct number of filehandles to be read (i.e. both normal and File::Tails). Once select returns, when you want to determine which File::Tail objects have input ready, you can either use the list of objects select returned, or you can check each individual object with $object->predict. This returns the ammount of time (in fractional seconds) after which the handle expects input. If it returns 0, there is input waiting. There is no guarantee that there will be input waiting after the returned number of seconds has passed. However, File::Tail won't do any I/O on the file until that time has passed. Also note, if you are determining which files are ready for input by calling each individual predict, the `$nfound' value may be invalid, because one or more of File::Tail object may have become ready between the time select has returned and the time when you checked it. TO BE DONE ========== Planned for 0.95-1.0: Using $/ instead of \n to separate "lines" (which should make it possible to read wtmp type files). AUTHOR ====== Matija Grabnar, matija.grabnar@arnes.si SEE ALSO ======== perl(1), tail (1), MRTG (http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html)  File: pm.info, Node: File/Temp, Next: File/chmod, Prev: File/Tail, Up: Module List return name and handle of a temporary file safely ************************************************* NAME ==== File::Temp - return name and handle of a temporary file safely PORTABILITY =========== This module is designed to be portable across operating systems and it currently supports Unix, VMS, DOS, OS/2 and Windows. When porting to a new OS there are generally three main issues that have to be solved: * Can the OS unlink an open file? If it can not then the `_can_unlink_opened_file' method should be modified. * Are the return values from stat reliable? By default all the return values from stat are compared when unlinking a temporary file using the filename and the handle. Operating systems other than unix do not always have valid entries in all fields. If unlink0 fails then the stat comparison should be modified accordingly. * Security. Systems that can not support a test for the sticky bit on a directory can not use the MEDIUM and HIGH security tests. The `_can_do_level' method should be modified accordingly. SYNOPSIS ======== use File::Temp qw/ tempfile tempdir /; $dir = tempdir( CLEANUP => 1 ); ($fh, $filename) = tempfile( DIR => $dir ); ($fh, $filename) = tempfile( $template, DIR => $dir); ($fh, $filename) = tempfile( $template, SUFFIX => '.dat'); $fh = tempfile(); MkTemp family: use File::Temp qw/ :mktemp /; ($fh, $file) = mkstemp( "tmpfileXXXXX" ); ($fh, $file) = mkstemps( "tmpfileXXXXXX", $suffix); $tmpdir = mkdtemp( $template ); $unopened_file = mktemp( $template ); POSIX functions: use File::Temp qw/ :POSIX /; $file = tmpnam(); $fh = tmpfile(); ($fh, $file) = tmpnam(); ($fh, $file) = tmpfile(); Compatibility functions: $unopened_file = File::Temp::tempnam( $dir, $pfx ); Objects (NOT YET IMPLEMENTED): require File::Temp; $fh = new File::Temp($template); $fname = $fh->filename; DESCRIPTION =========== `File::Temp' can be used to create and open temporary files in a safe way. The tempfile() function can be used to return the name and the open filehandle of a temporary file. The tempdir() function can be used to create a temporary directory. The security aspect of temporary file creation is emphasized such that a filehandle and filename are returned together. This helps guarantee that a race condition can not occur where the temporary file is created by another process between checking for the existence of the file and its opening. Additional security levels are provided to check, for example, that the sticky bit is set on world writable directories. See `"safe_level"' in this node for more information. For compatibility with popular C library functions, Perl implementations of the mkstemp() family of functions are provided. These are, mkstemp(), mkstemps(), mkdtemp() and mktemp(). Additionally, implementations of the standard `POSIX|POSIX' in this node tmpnam() and tmpfile() functions are provided if required. Implementations of mktemp(), tmpnam(), and tempnam() are provided, but should be used with caution since they return only a filename that was valid when function was called, so cannot guarantee that the file will not exist by the time the caller opens the filename. FUNCTIONS ========= This section describes the recommended interface for generating temporary files and directories. tempfile This is the basic function to generate temporary files. The behaviour of the file can be changed using various options: ($fh, $filename) = tempfile(); Create a temporary file in the directory specified for temporary files, as specified by the tmpdir() function in *Note File/Spec: File/Spec,. ($fh, $filename) = tempfile($template); Create a temporary file in the current directory using the supplied template. Trailing `X' characters are replaced with random letters to generate the filename. At least four `X' characters must be present in the template. ($fh, $filename) = tempfile($template, SUFFIX => $suffix) Same as previously, except that a suffix is added to the template after the `X' translation. Useful for ensuring that a temporary filename has a particular extension when needed by other applications. But see the WARNING at the end. ($fh, $filename) = tempfile($template, DIR => $dir); Translates the template as before except that a directory name is specified. ($fh, $filename) = tempfile($template, UNLINK => 1); Return the filename and filehandle as before except that the file is automatically removed when the program exits. Default is for the file to be removed if a file handle is requested and to be kept if the filename is requested. In a scalar context (where no filename is returned) the file is always deleted either on exit or when it is closed. If the template is not specified, a template is always automatically generated. This temporary file is placed in tmpdir() (*Note File/Spec: File/Spec,) unless a directory is specified explicitly with the DIR option. $fh = tempfile( $template, DIR => $dir ); If called in scalar context, only the filehandle is returned and the file will automatically be deleted when closed (see the description of tmpfile() elsewhere in this document). This is the preferred mode of operation, as if you only have a filehandle, you can never create a race condition by fumbling with the filename. On systems that can not unlink an open file or can not mark a file as temporary when it is opened (for example, Windows NT uses the `O_TEMPORARY' flag)) the file is marked for deletion when the program ends (equivalent to setting UNLINK to 1). The `UNLINK' flag is ignored if present. (undef, $filename) = tempfile($template, OPEN => 0); This will return the filename based on the template but will not open this file. Cannot be used in conjunction with UNLINK set to true. Default is to always open the file to protect from possible race conditions. A warning is issued if warnings are turned on. Consider using the tmpnam() and mktemp() functions described elsewhere in this document if opening the file is not required. Options can be combined as required. tempdir This is the recommended interface for creation of temporary directories. The behaviour of the function depends on the arguments: $tempdir = tempdir(); Create a directory in tmpdir() (see `File::Spec|File::Spec' in this node). $tempdir = tempdir( $template ); Create a directory from the supplied template. This template is similar to that described for tempfile(). `X' characters at the end of the template are replaced with random letters to construct the directory name. At least four `X' characters must be in the template. $tempdir = tempdir ( DIR => $dir ); Specifies the directory to use for the temporary directory. The temporary directory name is derived from an internal template. $tempdir = tempdir ( $template, DIR => $dir ); Prepend the supplied directory name to the template. The template should not include parent directory specifications itself. Any parent directory specifications are removed from the template before prepending the supplied directory. $tempdir = tempdir ( $template, TMPDIR => 1 ); Using the supplied template, creat the temporary directory in a standard location for temporary files. Equivalent to doing $tempdir = tempdir ( $template, DIR => File::Spec->tmpdir); but shorter. Parent directory specifications are stripped from the template itself. The TMPDIR option is ignored if DIR is set explicitly. Additionally, TMPDIR is implied if neither a template nor a directory are supplied. $tempdir = tempdir( $template, CLEANUP => 1); Create a temporary directory using the supplied template, but attempt to remove it (and all files inside it) when the program exits. Note that an attempt will be made to remove all files from the directory even if they were not created by this module (otherwise why ask to clean it up?). The directory removal is made with the rmtree() function from the `File::Path|File::Path' in this node module. Of course, if the template is not specified, the temporary directory will be created in tmpdir() and will also be removed at program exit. MKTEMP FUNCTIONS ================ The following functions are Perl implementations of the mktemp() family of temp file generation system calls. mkstemp Given a template, returns a filehandle to the temporary file and the name of the file. ($fh, $name) = mkstemp( $template ); In scalar context, just the filehandle is returned. The template may be any filename with some number of X's appended to it, for example `/tmp/temp.XXXX'. The trailing X's are replaced with unique alphanumeric combinations. mkstemps Similar to mkstemp(), except that an extra argument can be supplied with a suffix to be appended to the template. ($fh, $name) = mkstemps( $template, $suffix ); For example a template of `testXXXXXX' and suffix of `.dat' would generate a file similar to `testhGji_w.dat'. Returns just the filehandle alone when called in scalar context. mkdtemp Create a directory from a template. The template must end in X's that are replaced by the routine. $tmpdir_name = mkdtemp($template); Returns the name of the temporary directory created. Returns undef on failure. Directory must be removed by the caller. mktemp Returns a valid temporary filename but does not guarantee that the file will not be opened by someone else. $unopened_file = mktemp($template); Template is the same as that required by mkstemp(). POSIX FUNCTIONS =============== This section describes the re-implementation of the tmpnam() and tmpfile() functions described in *Note POSIX: POSIX, using the mkstemp() from this module. Unlike the `POSIX|POSIX' in this node implementations, the directory used for the temporary file is not specified in a system include file (`P_tmpdir') but simply depends on the choice of tmpdir() returned by `File::Spec|File::Spec' in this node. On some implementations this location can be set using the TMPDIR environment variable, which may not be secure. If this is a problem, simply use mkstemp() and specify a template. tmpnam When called in scalar context, returns the full name (including path) of a temporary file (uses mktemp()). The only check is that the file does not already exist, but there is no guarantee that that condition will continue to apply. $file = tmpnam(); When called in list context, a filehandle to the open file and a filename are returned. This is achieved by calling mkstemp() after constructing a suitable template. ($fh, $file) = tmpnam(); If possible, this form should be used to prevent possible race conditions. See `tmpdir', *Note File/Spec: File/Spec, for information on the choice of temporary directory for a particular operating system. tmpfile In scalar context, returns the filehandle of a temporary file. $fh = tmpfile(); The file is removed when the filehandle is closed or when the program exits. No access to the filename is provided. If the temporary file can not be created undef is returned. Currently this command will probably not work when the temporary directory is on an NFS file system. ADDITIONAL FUNCTIONS ==================== These functions are provided for backwards compatibility with common tempfile generation C library functions. They are not exported and must be addressed using the full package name. tempnam Return the name of a temporary file in the specified directory using a prefix. The file is guaranteed not to exist at the time the function was called, but such guarantees are good for one clock tick only. Always use the proper form of sysopen with `O_CREAT | O_EXCL' if you must open such a filename. $filename = File::Temp::tempnam( $dir, $prefix ); Equivalent to running mktemp() with $dir/$prefixXXXXXXXX (using unix file convention as an example) Because this function uses mktemp(), it can suffer from race conditions. UTILITY FUNCTIONS ================= Useful functions for dealing with the filehandle and filename. unlink0 Given an open filehandle and the associated filename, make a safe unlink. This is achieved by first checking that the filename and filehandle initially point to the same file and that the number of links to the file is 1 (all fields returned by stat() are compared). Then the filename is unlinked and the filehandle checked once again to verify that the number of links on that file is now 0. This is the closest you can come to making sure that the filename unlinked was the same as the file whose descriptor you hold. unlink0($fh, $path) or die "Error unlinking file $path safely"; Returns false on error. The filehandle is not closed since on some occasions this is not required. On some platforms, for example Windows NT, it is not possible to unlink an open file (the file must be closed first). On those platforms, the actual unlinking is deferred until the program ends and good status is returned. A check is still performed to make sure that the filehandle and filename are pointing to the same thing (but not at the time the end block is executed since the deferred removal may not have access to the filehandle). Additionally, on Windows NT not all the fields returned by stat() can be compared. For example, the dev and `rdev' fields seem to be different. Also, it seems that the size of the file returned by stat() does not always agree, with `stat(FH)' being more accurate than `stat(filename)', presumably because of caching issues even when using autoflush (this is usually overcome by waiting a while after writing to the tempfile before attempting to unlink0 it). Finally, on NFS file systems the link count of the file handle does not always go to zero immediately after unlinking. Currently, this command is expected to fail on NFS disks. PACKAGE VARIABLES ================= These functions control the global state of the package. safe_level Controls the lengths to which the module will go to check the safety of the temporary file or directory before proceeding. Options are: STANDARD Do the basic security measures to ensure the directory exists and is writable, that the umask() is fixed before opening of the file, that temporary files are opened only if they do not already exist, and that possible race conditions are avoided. Finally the `unlink0|"unlink0"' in this node function is used to remove files safely. MEDIUM In addition to the STANDARD security, the output directory is checked to make sure that it is owned either by root or the user running the program. If the directory is writable by group or by other, it is then checked to make sure that the sticky bit is set. Will not work on platforms that do not support the -k test for sticky bit. HIGH In addition to the MEDIUM security checks, also check for the possibility of "chown() giveaway" using the `POSIX|POSIX' in this node sysconf() function. If this is a possibility, each directory in the path is checked in turn for safeness, recursively walking back to the root directory. For platforms that do not support the `POSIX|POSIX' in this node `_PC_CHOWN_RESTRICTED' symbol (for example, Windows NT) it is assumed that "chown() giveaway" is possible and the recursive test is performed. The level can be changed as follows: File::Temp->safe_level( File::Temp::HIGH ); The level constants are not exported by the module. Currently, you must be running at least perl v5.6.0 in order to run with MEDIUM or HIGH security. This is simply because the safety tests use functions from `Fcntl|Fcntl' in this node that are not available in older versions of perl. The problem is that the version number for Fcntl is the same in perl 5.6.0 and in 5.005_03 even though they are different versions. On systems that do not support the HIGH or MEDIUM safety levels (for example Win NT or OS/2) any attempt to change the level will be ignored. The decision to ignore rather than raise an exception allows portable programs to be written with high security in mind for the systems that can support this without those programs failing on systems where the extra tests are irrelevant. If you really need to see whether the change has been accepted simply examine the return value of safe_level. $newlevel = File::Temp->safe_level( File::Temp::HIGH ); die "Could not change to high security" if $newlevel != File::Temp::HIGH; TopSystemUID This is the highest UID on the current system that refers to a root UID. This is used to make sure that the temporary directory is owned by a system UID (root, bin, sys etc) rather than simply by root. This is required since on many unix systems `/tmp' is not owned by root. Default is to assume that any UID less than or equal to 10 is a root UID. File::Temp->top_system_uid(10); my $topid = File::Temp->top_system_uid; This value can be adjusted to reduce security checking if required. The value is only relevant when safe_level is set to MEDIUM or higher. WARNING ======= For maximum security, endeavour always to avoid ever looking at, touching, or even imputing the existence of the filename. You do not know that that filename is connected to the same file as the handle you have, and attempts to check this can only trigger more race conditions. It's far more secure to use the filehandle alone and dispense with the filename altogether. If you need to pass the handle to something that expects a filename then, on a unix system, use `"/dev/fd/" . fileno($fh)' for arbitrary programs, or more generally `< "+<=&" . fileno($fh) '> for Perl programs. You will have to clear the close-on-exec bit on that file descriptor before passing it to another process. use Fcntl qw/F_SETFD F_GETFD/; fcntl($tmpfh, F_SETFD, 0) or die "Can't clear close-on-exec flag on temp fh: $!\n"; Temporary files and NFS ----------------------- Some problems are associated with using temporary files that reside on NFS file systems and it is recommended that a local filesystem is used whenever possible. Some of the security tests will most probably fail when the temp file is not local. Additionally, be aware that the performance of I/O operations over NFS will not be as good as for a local disk. HISTORY ======= Originally began life in May 1999 as an XS interface to the system mkstemp() function. In March 2000, the OpenBSD mkstemp() code was translated to Perl for total control of the code's security checking, to ensure the presence of the function regardless of operating system and to help with portability. SEE ALSO ======== `tmpnam', *Note POSIX: POSIX,, `tmpfile', *Note POSIX: POSIX,, `tmpfile', *Note File/Spec: File/Spec,, `tmpfile', *Note File/Path: File/Path, See *Note IO/File: IO/File, and *Note File/MkTemp: File/MkTemp, for different implementations of temporary file handling. AUTHOR ====== Tim Jenness Copyright (C) 1999-2001 Tim Jenness and the UK Particle Physics and Astronomy Research Council. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Original Perl implementation loosely based on the OpenBSD C code for mkstemp(). Thanks to Tom Christiansen for suggesting that this module should be written and providing ideas for code improvements and security enhancements.