1Directory::Scratch(3) User Contributed Perl DocumentationDirectory::Scratch(3)
2
3
4
6 Directory::Scratch - Easy-to-use self-cleaning scratch space.
7
9 When writing test suites for modules that operate on files, it's often
10 inconvenient to correctly create a platform-independent temporary
11 storage space, manipulate files inside it, then clean it up when the
12 test exits. The inconvenience usually results in tests that don't work
13 everwhere, or worse, no tests at all.
14
15 This module aims to eliminate that problem by making it easy to do
16 things right.
17
18 Example:
19
20 use Directory::Scratch;
21
22 my $temp = Directory::Scratch->new();
23 my $dir = $temp->mkdir('foo/bar');
24 my @lines= qw(This is a file with lots of lines);
25 my $file = $temp->touch('foo/bar/baz', @lines);
26
27 my $fh = openfile($file);
28 print {$fh} "Here is another line.\n";
29 close $fh;
30
31 $temp->delete('foo/bar/baz');
32
33 undef $temp; # everything else is removed
34
35 # Directory::Scratch objects stringify to base
36 $temp->touch('foo');
37 ok(-e "$temp/foo"); # /tmp/xYz837/foo should exist
38
40 The first argument to the module is optional, but if specified, it's
41 interperted as the name of the OS whose file naming semantics you want
42 to use with Directory::Scratch. For example, if you choose "Unix",
43 then you can provide paths to Directory::Scratch in UNIX-form
44 ('foo/bar/baz') on any platform. Unix is the default if you don't
45 choose anything explicitly.
46
47 If you want to use the local platform's flavor (not recommended),
48 specify an empty import list:
49
50 use Directory::Scratch ''; # use local path flavor
51
52 Recognized platforms (from File::Spec):
53
54 Mac
55 UNIX
56 Win32
57 VMS
58 OS2
59
60 The names are case sensitive, since they simply specify which
61 "File::Spec::" module to use when splitting the path.
62
63 EXAMPLE
64 use Directory::Scratch 'Win32';
65 my $tmp = Directory::Scratch->new();
66 $tmp->touch("foo\\bar\\baz"); # and so on
67
69 The file arguments to these methods are always relative to the
70 temporary directory. If you specify "touch('/etc/passwd')", then a
71 file called "/tmp/whatever/etc/passwd" will be created instead.
72
73 This means that the program's PWD is ignored (for these methods), and
74 that a leading "/" on the filename is meaningless (and will cause
75 portability problems).
76
77 Finally, whenever a filename or path is returned, it is a Path::Class
78 object rather than a string containing the filename. Usually, this
79 object will act just like the string, but to be extra-safe, call
80 "$path->stringify" to ensure that you're really getting a string.
81 (Some clever modules try to determine whether a variable is a filename
82 or a filehandle; these modules usually guess wrong when confronted with
83 a "Path::Class" object.)
84
85 new
86 Creates a new temporary directory (via File::Temp and its defaults).
87 When the object returned by this method goes out of scope, the
88 directory and its contents are removed.
89
90 my $temp = Directory::Scratch->new;
91 my $another = $temp->new(); # will be under $temp
92
93 # some File::Temp arguments get passed through (may be less portable)
94 my $temp = Directory::Scratch->new(
95 DIR => '/var/tmp', # be specific about where your files go
96 CLEANUP => 0, # turn off automatic cleanup
97 TEMPLATE => 'ScratchDirXXXX', # specify a template for the dirname
98 );
99
100 If "DIR", "CLEANUP", or "TEMPLATE" are omitted, reasonable defaults are
101 selected. "CLEANUP" is on by default, and "DIR" is set to
102 "File::Spec-"tmpdir>;
103
104 child
105 Creates a new "Directory::Scratch" directory inside the current "base",
106 copying TEMPLATE and CLEANUP options from the current instance.
107 Returns a "Directory::Scratch" object.
108
109 base
110 Returns the full path of the temporary directory, as a Path::Class
111 object.
112
113 platform([$platform])
114 Returns the name of the platform that the filenames are being
115 interperted as (i.e., "Win32" means that this module expects paths like
116 "\foo\bar", whereas "UNIX" means it expects "/foo/bar").
117
118 If $platform is sepcified, the platform is changed to the passed value.
119 (Overrides the platform specified at module "use" time, for this
120 instance only, not every "Directory::Scratch" object.)
121
122 touch($filename, [@lines])
123 Creates a file named $filename, optionally containing the elements of
124 @lines separated by the output record separator "$\".
125
126 The Path::Class object representing the new file is returned if the
127 operation is successful, an exception is thrown otherwise.
128
129 create_tree(%tree)
130 Creates a file for every key/value pair if the hash, using the key as
131 the filename and the value as the contents. If the value is an
132 arrayref, the array is used as the optional @lines argument to "touch".
133 If the value is a reference to "undef", then a directory is created
134 instead of a file.
135
136 Example:
137
138 %tree = ( 'foo' => 'this is foo',
139 'bar/baz' => 'this is baz inside bar',
140 'lines' => [qw|this file contains 5 lines|],
141 'dir' => \undef,
142 );
143 $tmp->create_tree(%tree);
144
145 In this case, two directories are created, "dir" and "bar"; and three
146 files are created, "foo", "baz" (inside "bar"), and "lines". "foo" and
147 "baz" contain a single line, while "lines" contains 5 lines.
148
149 openfile($filename)
150 Opens $filename for writing and reading ("+>"), and returns the
151 filehandle. If $filename already exists, it will be truncated. It's
152 up to you to take care of flushing/closing.
153
154 In list context, returns both the filehandle and the filename "($fh,
155 $path)".
156
157 mkdir($directory)
158 Creates a directory (and its parents, if necessary) inside the
159 temporary directory and returns its name. Any leading "/" on the
160 directory name is ignored; all directories are created inside the
161 "base".
162
163 The full path of this directory is returned if the operation is
164 successful, otherwise an exception is thrown.
165
166 tempfile([$path])
167 Returns an empty filehandle + filename in $path. If $path is omitted,
168 the base directory is assumed.
169
170 See File::Temp::tempfile.
171
172 my($fh,$name) = $scratch->tempfile;
173
174 exists($file)
175 Returns the file's real (system) path if $file exists, undefined
176 otherwise.
177
178 Example:
179
180 my $path = $tmp->exists($file);
181 if(defined $path){
182 say "Looks like you have a file at $path!";
183 open(my $fh, '>>', $path) or die $!;
184 print {$fh} "add another line\n";
185 close $fh or die $!;
186 }
187 else {
188 say "No file called $file."
189 }
190
191 stat($file)
192 Stats $file. In list context, returns the list returned by the "stat"
193 builtin. In scalar context, returns a "File::stat" object.
194
195 read($file)
196 Returns the contents of $file. In array context, returns a list of
197 chompped lines. In scalar context, returns the raw octets of the file
198 (with any trailing newline removed).
199
200 If you wrote the file with $, set, you'll want to set $/ to $, when
201 reading the file back in:
202
203 local $, = '!';
204 $tmp->touch('foo', qw{foo bar baz}); # writes "foo!bar!baz!" to disk
205 scalar $tmp->read('foo') # returns "foo!bar!baz!"
206 $tmp->read('foo') # returns ("foo!bar!baz!")
207 local $/ = '!';
208 $tmp->read('foo') # returns ("foo", "bar", "baz")
209
210 write($file, @lines)
211 Replaces the contents of file with @lines. Each line will be ended
212 with a "\n", or $, if it is defined. The file will be created if
213 necessary.
214
215 append($file, @lines)
216 Appends @lines to $file, as per "write".
217
218 randfile()
219 Generates a file with random string data in it. If String::Random is
220 available, it will be used to generate the file's data. Takes 0, 1, or
221 2 arguments - default size, max size, or size range.
222
223 A max size of 0 will cause an exception to be thrown.
224
225 Examples:
226
227 my $file = $temp->randfile(); # size is between 1024 and 131072
228 my $file = $temp->randfile( 4192 ); # size is below 4129
229 my $file = $temp->randfile( 1000000, 4000000 );
230
231 link($from, $to)
232 Symlinks a file in the temporary directory to another file in the
233 temporary directory.
234
235 Note: symlinks are not supported on Win32. Portable code must not use
236 this method. (The method will "croak" if it won't work.)
237
238 ls([$path])
239 Returns a list (in no particular order) of all files below $path. If
240 $path is omitted, the root is assumed. Note that directories are not
241 returned.
242
243 If $path does not exist, an exception is thrown.
244
245 delete($path)
246 Deletes the named file or directory at $path.
247
248 If the path is removed successfully, the method returns true.
249 Otherwise, an exception is thrown.
250
251 (Note: delete means "unlink" for a file and "rmdir" for a directory.
252 "delete"-ing an unempty directory is an error.)
253
254 chmod($octal_permissions, @files)
255 Sets the permissions $octal_permissions on @files, returning the number
256 of files successfully changed. Note that '0644' is "--w----r-T", not
257 "-rw-r--r--". You need to pass in "oct('0644')" or a literal 0644 for
258 this method to DWIM. The method is just a passthru to perl's built-in
259 "chmod" function, so see "perldoc -f chmod" for full details.
260
261 cleanup
262 Forces an immediate cleanup of the current object's directory. See
263 File::Path's rmtree(). It is not safe to use the object after this
264 method is called.
265
267 If the "PERL_DIRECTORYSCRATCH_CLEANUP" variable is set to 0, automatic
268 cleanup will be suppressed.
269
271 Commentary, patches, etc. are most welcome. If you send a patch, try
272 patching the git version available from:
273
274 git://git.jrock.us/Directory-Scratch <git://git.jrock.us/Directory-
275 Scratch>.
276
277 You can check out a copy by running:
278
279 git clone git://git.jrock.us/Directory-Scratch
280
281 Then you can use git to commit changes and then e-mail me a patch, or
282 you can publish the repository and ask me to pull the changes. More
283 information about git is available from
284
285 <http://git.or.cz/>
286
288 L<File::Temp>
289 L<File::Path>
290 L<File::Spec>
291 L<Path::Class>
292
294 Please report any bugs or feature through the web interface at
295 http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Directory-Scratch
296 <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Directory-Scratch>.
297
299 Thanks to Al Tobey (TOBEYA) for some excellent patches, notably:
300
301 "child"
302 Random Files ("randfile")
303 "tempfile"
304 "openfile"
305
307 Copyright 2006 Jonathan Rockway, all rights reserved.
308
309 This program is free software; you can redistribute it and/or modify it
310 under the same terms as Perl itself.
311
312
313
314perl v5.12.0 2008-06-09 Directory::Scratch(3)