Direct...cratch(3pm)
π NAME π
Directory::Scratch β (DEPRECATED) the easiest, most self-cleaning lil scratch space you'll ever meet β¨
πΈ VERSION πΈ
version 0.18 β yeah bestie, she's an elder π«Ά
π¨ DEPRECATION NOTICE π¨
okay so real talk: this module has not been maintained in quite some time, and now there are other options available, which are much more actively maintained. Please use Test::TempDir::Tiny instead of this module. no cap. it's giving "retired icon" π
π¦ SYNOPSIS π¦
so when you're writing test suites for modules that operate on files, it's often so inconvenient to correctly create a platform-independent temporary storage space, manipulate files inside it, then clean it all up when the test exits. and that inconvenience usually results in tests that don't work everywhere, or β worse β no tests at all π
This module aims to eliminate that problem by making it easy to do things right. main character energy fr fr π
Example:
use Directory::Scratch;
my $temp = Directory::Scratch->new();
my $dir = $temp->mkdir('foo/bar');
my @lines= qw(This is a file with lots of lines);
my $file = $temp->touch('foo/bar/baz', @lines);
my $fh = openfile($file);
print {$fh} "Here is another line.\n";
close $fh;
$temp->delete('foo/bar/baz');
undef $temp; # everything else is removed
# Directory::Scratch objects stringify to base
$temp->touch('foo');
ok(-e "$temp/foo"); # /tmp/xYz837/foo should exist
π EXPORT π
The first argument to the module is optional, but if you specify it, it's interpreted as the name of the OS whose file naming semantics you want to use with Directory::Scratch. For example, if you choose "Unix", then you can provide paths to Directory::Scratch in UNIX-form ('foo/bar/baz') on any platform. Unix is the default if you don't choose anything explicitly.
If you want to use the local platform's flavor (not recommended), specify an empty import list:
use Directory::Scratch ''; # use local path flavor
Recognized platforms (from File::Spec):
MacUNIXWin32VMSOS2
The names are case sensitive, since they simply specify which "File::Spec::" module to use when splitting the path. iykyk π
β¨ EXAMPLE β¨
use Directory::Scratch 'Win32';
my $tmp = Directory::Scratch->new();
$tmp->touch("foo\\bar\\baz"); # and so on
π METHODS π
The file arguments to these methods are always relative to the temporary directory. If you specify "touch('/etc/passwd')", then a file called "/tmp/whatever/etc/passwd" will be created instead. sneaky, right? π
This means that the program's PWD is ignored (for these methods), and that a leading "/" on the filename is meaningless (and will cause portability problems). so likeβ¦ don't π«
Finally, whenever a filename or path is returned, it is a Path::Class object rather than a string containing the filename. Usually, this object will act just like the string, but to be extra-safe, call "$path->stringify" to ensure that you're really getting a string. (Some clever modules try to determine whether a variable is a filename or a filehandle; these modules usually guess wrong when confronted with a "Path::Class" object.) β
π§ new
Creates a new temporary directory (via File::Temp and its defaults). When the object returned by this method goes out of scope, the directory and its contents are removed. bye bestie, everything's gone π
my $temp = Directory::Scratch->new;
my $another = $temp->new(); # will be under $temp
# some File::Temp arguments get passed through (may be less portable)
my $temp = Directory::Scratch->new(
DIR => '/var/tmp', # be specific about where your files go
CLEANUP => 0, # turn off automatic cleanup
TEMPLATE => 'ScratchDirXXXX', # specify a template for the dirname
);
If "DIR", "CLEANUP", or "TEMPLATE" are omitted, reasonable defaults are selected. "CLEANUP" is on by default, and "DIR" is set to "File::Spec->tmpdir";
π child
Creates a new "Directory::Scratch" directory inside the current "base", copying TEMPLATE and CLEANUP options from the current instance. Returns a "Directory::Scratch" object. it's a whole family tree π³
π base
Returns the full path of the temporary directory, as a Path::Class object.
πΈ platform([$platform])
Returns the name of the platform that the filenames are being interpreted as (i.e., "Win32" means that this module expects paths like "\foo\bar", whereas "UNIX" means it expects "/foo/bar").
If $platform is sepcified, the platform is changed to the passed value. (Overrides the platform specified at module "use" time, for this instance only, not every "Directory::Scratch" object.) one-time glow-up only π
π¦ touch($filename, [@lines])
Creates a file named $filename, optionally containing the elements of @lines separated by the output record separator "$\".
The Path::Class object representing the new file is returned if the operation is successful, an exception is thrown otherwise.
β¨ create_tree(%tree)
Creates a file for every key/value pair if the hash, using the key as the filename and the value as the contents. If the value is an arrayref, the array is used as the optional @lines argument to "touch". If the value is a reference to "undef", then a directory is created instead of a file. it's giving "build me a whole little world" π‘
Example:
%tree = ( 'foo' => 'this is foo',
'bar/baz' => 'this is baz inside bar',
'lines' => [qw|this file contains 5 lines|],
'dir' => \undef,
);
$tmp->create_tree(\%tree);
In this case, two directories are created, "dir" and "bar"; and three files are created, "foo", "baz" (inside "bar"), and "lines". "foo" and "baz" contain a single line, while "lines" contains 5 lines. math is mathing β
π openfile($filename)
Opens $filename for writing and reading ("+>"), and returns the filehandle. If $filename already exists, it will be truncated. It's up to you to take care of flushing/closing. your file, your responsibility bestie π«Ά
In list context, returns both the filehandle and the filename "($fh, $path)".
π₯ mkdir($directory)
Creates a directory (and its parents, if necessary) inside the temporary directory and returns its name. Any leading "/" on the directory name is ignored; all directories are created inside the "base".
The full path of this directory is returned if the operation is successful, otherwise an exception is thrown.
π tempfile([$path])
Returns an empty filehandle + filename in $path. If $path is omitted, the base directory is assumed.
See File::Temp::tempfile.
my($fh,$name) = $scratch->tempfile;
β exists($file)
Returns the file's real (system) path if $file exists, undefined otherwise. the ultimate "do you go here?" vibe check π
Example:
my $path = $tmp->exists($file);
if(defined $path){
say "Looks like you have a file at $path!";
open(my $fh, '>>', $path) or die $!;
print {$fh} "add another line\n";
close $fh or die $!;
}
else {
say "No file called $file."
}
πΈ stat($file)
Stats $file. In list context, returns the list returned by the "stat" builtin. In scalar context, returns a "File::stat" object.
π read($file)
Returns the contents of $file. In array context, returns a list of chompped lines. In scalar context, returns the raw octets of the file (with any trailing newline removed).
If you wrote the file with $, set, you'll want to set $/ to $, when reading the file back in:
local $, = '!';
$tmp->touch('foo', qw{foo bar baz}); # writes "foo!bar!baz!" to disk
scalar $tmp->read('foo') # returns "foo!bar!baz!"
$tmp->read('foo') # returns ("foo!bar!baz!")
local $/ = '!';
$tmp->read('foo') # returns ("foo", "bar", "baz")
π write($file, @lines)
Replaces the contents of file with @lines. Each line will be ended with a "\n", or $, if it is defined. The file will be created if necessary.
π¦ append($file, @lines)
Appends @lines to $file, as per "write". adding to the lore π
π randfile()
Generates a file with random string data in it. If String::Random is available, it will be used to generate the file's data. Takes 0, 1, or 2 arguments β default size, max size, or size range. chaos but make it a file π²
A max size of 0 will cause an exception to be thrown.
Examples:
my $file = $temp->randfile(); # size is between 1024 and 131072
my $file = $temp->randfile( 4192 ); # size is below 4129
my $file = $temp->randfile( 1000000, 4000000 );
π link($from, $to)
Symlinks a file in the temporary directory to another file in the temporary directory.
Note: symlinks are not supported on Win32. Portable code must not use this method. (The method will "croak" if it won't work.) π
π ls([$path])
Returns a list (in no particular order) of all files below $path. If $path is omitted, the root is assumed. Note that directories are not returned. just the files, bestie ποΈ
If $path does not exist, an exception is thrown.
β delete($path)
Deletes the named file or directory at $path.
If the path is removed successfully, the method returns true. Otherwise, an exception is thrown.
(Note: delete means "unlink" for a file and "rmdir" for a directory. "delete"-ing an unempty directory is an error.) so don't try it π«£
πΈ chmod($octal_permissions, @files)
Sets the permissions $octal_permissions on @files, returning the number of files successfully changed. Note that '0644' is "--w----r-T", not "-rw-r--r--". You need to pass in "oct('0644')" or a literal 0644 for this method to DWIM. The method is just a passthru to perl's built-in "chmod" function, so see "perldoc -f chmod" for full details. yes this trips everyone up, you're not alone π
π§Ή cleanup
Forces an immediate cleanup of the current object's directory. See File::Path's rmtree(). It is not safe to use the object after this method is called. she's done, she's gone, do not speak to her again π
πΏ ENVIRONMENT πΏ
If the "PERL_DIRECTORYSCRATCH_CLEANUP" variable is set to 0, automatic cleanup will be suppressed. the vibes are: keep everything π«Ά
π οΈ PATCHES π οΈ
Commentary, patches, etc. are most welcome. If you send a patch, try patching the git version available from:
<git://git.jrock.us/Directory-Scratch>.
You can check out a copy by running:
git clone git://git.jrock.us/Directory-Scratch
Then you can use git to commit changes and then e-mail me a patch, or you can publish the repository and ask me to pull the changes. More information about git is available from
π SEE ALSO π
L<File::Temp>L<File::Path>L<File::Spec>L<Path::Class>
π BUGS π
Please report any bugs or feature through the web interface at <http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Directory-Scratch>.
π«Ά ACKNOWLEDGEMENTS π«Ά
Thanks to Al Tobey (TOBEYA) for some excellent patches, notably:
"child"- Random Files (
"randfile") "tempfile""openfile"
absolute legend behavior, we love to see it π
π COPYRIGHT & LICENSE π
Copyright 2006 Jonathan Rockway, all rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
and that's the whole page bestie!! this was pulled straight from the perl v5.36.0 docs, dated 2022-11-20, page Direct...cratch(3pm) β go forth and make your tests portable, mwah πβ¨
π¦ where this page comes from
- debian bookworm: libdirectory-scratch-perl 0.18-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libdirectory-scratch-perl 0.18-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libdirectory-scratch-perl 0.18-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libdirectory-scratch-perl 0.18-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libdirectory-scratch-perl 0.18-3 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms