File::Save::Home(3pm)

πŸ“¦
version 0.12 Β· 3 versions
, in ubuntu resolute, ubuntu stonking

πŸ’– File::Save::Home(3pm) πŸ’–

User Contributed Perl Documentation Β· bestie edition Β· part 1 of 2


✨ NAME ✨

File::Save::Home β€” Place file safely under user home directory 🏠✨

🌸 VERSION 🌸

okay so this document is talking about version 0.12, released January 03 2026. noted, bestie πŸ“Œ

πŸ¦‹ SYNOPSIS πŸ¦‹

use File::Save::Home qw(
    get_home_directory
    get_subhome_directory_status
    make_subhome_directory
    restore_subhome_directory_status
    conceal_target_file
    reveal_target_file
    make_subhome_temp_directory
);

$home_dir = get_home_directory();

$desired_dir_ref = get_subhome_directory_status("desired/directory");

$desired_dir_ref = get_subhome_directory_status(
    "desired/directory",
    "pseudohome/directory",    # two-argument version
);

$desired_dir = make_subhome_directory($desired_dir_ref);

restore_subhome_directory_status($desired_dir_ref);

$target_ref = conceal_target_file( {
    dir     => $desired_dir,
    file    => 'file_to_be_checked',
    test    => 0,
} );

reveal_target_file($target_ref);

$tmpdir = make_subhome_temp_directory();

$tmpdir = make_subhome_temp_directory(
    "pseudohome/directory",    # optional argument version
);

πŸ’… DESCRIPTION πŸ’…

Okay so picture this: you're deploying an application onto somebody else's system, and you lowkey need to drop a file into their home directory, or somewhere underneath it. Can you do that safely though?? 😭

This Perl extension says: say less, I got you. It hands you a whole set of functions that try to figure out whether you can, actually, safely create directories and files underneath a user's home directory. And here's the cute part β€” if you're only putting a file there temporarily (say, for testing purposes, bestie), you can temporarily hide any file that's already chilling there with the same name, and then restore it to its original name and its original timestamps when you're done. no cap, that's the whole vibe. πŸ’…

🚧 Limitations 🚧

That description up there? Written in 2005, bestie. Since then, experience has shown that any claim you make about the safety of creating or deleting directories and files underneath a user's home directory has to be qualified. File::Save::Home is satisfactory for the use case it was originally designed for, but there are other situations where it falls short. it's giving "good at one specific thing" πŸ˜”

The original use case it was designed for was supporting the placement of personal preference files in a user's home directory. Those are often called dot-rc files, because their names typically start with a . character (which renders them hidden from commands like ls) and end in rc, much like .bashrc or .shrc. A developer using CPAN::Mini, for example, often uses .minicpanrc to store their preferred CPAN mirror. File::Save::Home was created specifically to support:

  • the creation of a .modulemakerrc file by users of ExtUtils::ModuleMaker, and
  • a .podmultirc file by users of Pod::Multi.

(ExtUtils::ModuleMaker and Pod::Multi are maintained by the author of File::Save::Home, jsyk.)

These libraries are developer's tools, i.e., they're meant to help individual humans do software development rather than being used "in production." So their use of dot-rc files implicitly assumes:

  • Only one user is concerned with the status of the directories and files, including dot-rc files, underneath the user's home directory.
  • Only one user has permissions to create, modify or remove directories and files underneath the user's home directory β€” an assumption that is easily violated by a superuser such as "root".
  • The user is running processes to create, modify or remove directories and files underneath the user's home directory one-at-a-time, "i.e.," the user is not running such processes in parallel. Running such processes in parallel would raise the possibility, for example, of one process trying to rename a dot-rc file that a second, parallel process had already deleted. 😡

When either the second or the third assumption above is violated, we have the possibility of race conditions (<https://en.wikipedia.org/wiki/Race_condition>) and time of check to time of use (TOCTTOU) errors (<https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use>). Such conditions may lead to either spurious testing failures (e.g., when CPANtesteers run tests in parallel on libraries using File::Save::Home) or to security violations. so yeah, not a vibe. ⚠️

πŸŽ€ USAGE πŸŽ€

get_home_directory()

This one analyzes environmental information to figure out whether there exists on the system a 'HOME' or 'home-equivalent' directory. Takes no arguments. Returns that directory if it exists; croaks otherwise. πŸ”₯

On Win32, this directory is the one returned by the following function from the Win32 module:

Win32->import( qw(CSIDL_LOCAL_APPDATA) );
$realhome =  Win32::GetFolderPath( CSIDL_LOCAL_APPDATA() );

... which translates to something like C:\Documents and Settings\localuser\Local Settings\Application Data. (For a further discussion of Win32, see below "SEE ALSO".)

On Unix-like systems, things are much simpler, bestie. We just check the value of $ENV{HOME}. We can't do that on Win32 because $ENV{HOME} is not defined there. periodt. πŸ’…

get_subhome_directory_status()

Single argument version

Takes as argument a string holding the name of a directory, either single-level ("mydir") or multi-level ("path/to/mydir"). Determines whether that directory already exists underneath the user's home or home-equivalent directory. Calls get_home_directory() internally, then tacks on the path passed as argument. easy. ✨

Two-argument version

Okay so suppose you want to determine the name of a user's home directory by some other route than get_home_directory(). Suppose, for example, that you're on Win32 and want to use the my_home() method supplied by the CPAN distribution File::HomeDir β€” a method that returns a different result from that of our get_home_directory() β€” but you still want to use those File::Save::Home functions which normally call get_home_directory() internally. Or, suppose you want to supply an arbitrary path. 😌

You can now do so by supplying an optional second argument to get_subhome_directory_status. This argument should be a valid path name for a directory to which you have write privileges. get_subhome_directory_status will determine if the directory exists and, if so, determine whether the first argument is a subdirectory of the second argument. cute, right?

Both versions

Whether you use the single argument version or the two-argument version, get_subhome_directory_status returns a reference to a four-element hash whose keys are:

  • home β€” The absolute path of the home directory.
  • abs β€” The absolute path of the directory specified as first argument to the function.
  • flag β€” A Boolean value indicating whether the desired directory already exists (a true value) or not (undef).
  • top β€” The uppermost subdirectory passed as the argument to this function.

make_subhome_directory()

Takes as argument the hash reference returned by get_subhome_directory_status(). Examines the first element in that array β€” the directory name β€” and creates the directory if it doesn't already exist. The function croaks if the directory cannot be created. πŸ’€

restore_subhome_directory_status()

Undoes make_subhome_directory(), i.e., if there was no specified directory under the user's home directory on the user's system before testing, any such directory created during testing is removed. On the other hand, if there was such a directory present before testing, it is left unchanged. we love a function that knows when to not touch stuff. 🫢

make_subhome_temp_directory()

Regular version: no arguments

Creates a randomly named temporary directory underneath the home or home-equivalent directory returned by get_home_directory(). 🎲

Optional argument version

Creates a randomly named temporary directory underneath the directory supplied as the single argument. This version is analogous to the two-argument version of get_subhome_directory_status() above. You could use it if, for example, you wanted to use File::HomeDir->my_home() to supply a value for the user's home directory instead of our get_home_directory(). πŸ’«

Both versions

In both versions, the temporary subdirectory is created by calling:

File::Temp::tempdir(DIR => $home, CLEANUP => 1)

The function returns the directory path if successful; croaks otherwise.

Note: Any temporary directory so created remains in existence for the duration of the program, but is deleted (along with all its contents) when the program exits. so clean up your toys, bestie 🧹

conceal_target_file()

Determines whether a file with the specified name already exists in the specified directory and, if so, temporarily hides it by renaming it with a .hidden suffix, and stores away its last access and modification times. Takes as argument a reference to a hash with these keys:

  • dir β€” The directory in which the file is presumed to exist.
  • file β€” The targeted file, i.e., the file to be temporarily hidden if it already exists.
  • test β€” Boolean value which, if turned on (1), will cause the function, when called, to run two Test::More::ok() tests. Defaults to off (0).

Returns a reference to a hash with these keys:

  • full β€” The absolute path to the target file.
  • hidden β€” The absolute path to the now-hidden file.
  • atime β€” The last access time to the target file ((stat($file{full}))[8]).
  • modtime β€” The last modification time to the target file ((stat($file{full}))[9]).
  • test β€” The value of the key test in the hash passed by reference as an argument to this function.

reveal_target_file()

Used in conjunction with conceal_target_file() to restore the original status of the file targeted by conceal_target_file(), i.e., it renames the hidden file back to its original name by removing the .hidden suffix, thereby deleting any other file with the original name created between the calls to the two functions. croaks if the hidden file cannot be renamed. Takes as argument the hash reference returned by conceal_target_file(). If the value for the test key in the hash passed as an argument to conceal_target_file() was true, then a call to reveal_target_file will run three Test::More::ok() tests. it's giving "put it back exactly how you found it" energy πŸ’…

πŸ’€ BUGS AND TODO πŸ’€

So far tested only on Unix-like systems and Win32. that's the whole list, bestie. πŸ™ˆ


(part 2 incoming...)

✨ SEE ALSO ✨

okay so first up, the obvious one: perl(1) πŸ’… like, go read your perl manpage bestie, it's the mothership.

Then there's ExtUtils::ModuleMaker::Auxiliary and ExtUtils::ModuleMaker::Utility β€” those two are part of the ExtUtils::ModuleMaker distribution, which lives on CPAN and comes from the same author. And here's the tea: those two packages plus the ExtUtils::ModuleMaker test suite are literally full of examples of how people use File::Save::Home. Real-world receipts, no cap. 🧚

There's also one other CPAN distribution, File::HomeDir, that can locate a suitable value for a user's home directory too. BUT β€” and this is the important bit β€” this module and File::HomeDir take different approaches to defining a home directory on Win32 systems. So on any given system, each one may hand you a different result. 😭

And like, I'm not gonna sit here and say one distribution's approach is more correct or less correct than the other two's approaches. Nope. The comments below are just my subjective impressions β€” YMMV, periodt.

File::HomeDir was originally written by Sean M Burke and is now maintained by Adam Kennedy. As of version 0.52, its interface gives you three methods for the ''current user'':

$home = File::HomeDir->my_home;
$docs = File::HomeDir->my_documents;
$data = File::HomeDir->my_data;

When I ran these three methods on a Win2K Pro system running ActivePerl 8, here's what I got:

C:\WINNT\system32>perl -MFile::HomeDir -e "print File::HomeDir->my_home"
C:\Documents and Settings\localuser

C:\WINNT\system32>perl -MFile::HomeDir -e "print File::HomeDir->my_documents"
C:\Documents and Settings\localuser\My Documents

C:\WINNT\system32>perl -MFile::HomeDir -e "print File::HomeDir->my_data"
C:\Documents and Settings\localuser\Local Settings\Application Data

Meanwhile, when I ran the closest equivalent method in File::Save::Home, get_home_directory, I got this:

C:\WINNT\system32>perl -MFile::Save::Home -e "print File::Save::Home->get_home_directory"
C:\Documents and Settings\localuser\Local Settings\Application Data

So basically File::Save::Home->get_home_directory gave the same result as File::HomeDir->my_data β€” NOT the same result as File::HomeDir->my_home, which is what I might have expected. plot twist πŸ™ˆ

And the explanation? We gotta peek behind the curtain and look at the source code for each module. πŸ‘€


πŸ¦‹ File::HomeDir πŸ¦‹

File::HomeDir's whole mission is to provide a value for a user's home directory across a wide variety of operating systems. When you invoke it, it detects which OS you're on and calls a subclassed module. On a Win32 system, that subclass is called File::HomeDir::Windows. And File::HomeDir::Windows->my_home() looks like this:

sub my_home {
    my $class = shift;
    if ( $ENV{USERPROFILE} ) { return $ENV{USERPROFILE}; }
    if ( $ENV{HOMEDRIVE} and $ENV{HOMEPATH} ) {
            return File::Spec->catpath( $ENV{HOMEDRIVE}, $ENV{HOMEPATH}, '',);
    }
    Carp::croak("Could not locate current user's home directory");
}

In other words: figure out the current user's home directory just by checking environmental variables analogous to the $ENV{HOME} on Unix-like systems. Super straightforward approach! ⭐

But as mentioned above, File::Save::Home does it differently. It uses the Win32 module to, in effect, check a particular key in the registry:

Win32->import( qw(CSIDL_LOCAL_APPDATA) );
$realhome =  Win32::GetFolderPath( CSIDL_LOCAL_APPDATA() );

This approach was suggested to me in August 2005 by several members of Perlmonks. (See the threads Installing a config file during module operation (<http://perlmonks.org/?node_id=481690>) and Win32 CSIDL_LOCAL_APPDATA (<http://perlmonks.org/?node_id=485902>).) I adopted this approach partly because the people recommending it knew more about Windows than I did, and partly because File::HomeDir wasn't quite as mature back then as it has since become. 🌱

But don't trust me β€” trust Microsoft! Here's their explanation for using CSIDL values in general, and CSIDL_LOCAL_APPDATA() specifically:

  • CSIDL values provide a unique system-independent way to identify special folders used frequently by applications, but which may not have the same name or location on any given system. For example, the system folder may be ''C:\Windows'' on one system and ''C:\Winnt'' on another. These constants are defined in Shlobj.h and Shfolder.h.
  • CSIDL_LOCAL_APPDATA (0x001c) Version 5.0. The file system directory that serves as a data repository for local (nonroaming) applications. A typical path is C:\Documents and Settings\username\Local Settings\Application Data.

(Source: <http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp>. Link valid as of Feb 18 2006. Thanks to Soren Andersen for reminding me of this citation.) 🫢

It's honestly interesting that the other two File::HomeDir methods listed above β€” my_documents() and my_data() β€” both rely on using a Win32 module to peer into the registry, just in a slightly different manner from File::Save::Home->get_home_directory. TIMTOWTDI. πŸ’€ iconic.

Anyway! File::Save::Home has a whole bunch of useful methods besides get_home_directory() that genuinely merit your consideration. And, as noted above, you can supply any valid directory as an optional additional argument to the two File::Save::Home functions which normally default to calling get_home_directory internally. πŸ‘‘


πŸ’œ AUTHOR πŸ’œ

        James E Keenan
        CPAN ID: JKEENAN
        jkeenan@cpan.org
    https://metacpan.org/pod/File::Save::Home

πŸŽ€ ACKNOWLEDGMENTS πŸŽ€

File::Save::Home has its origins in the maintenance revisions I was doing on the CPAN distribution ExtUtils::ModuleMaker back in the summer of 2005. Then, after I made a presentation about that distribution to the Toronto Perlmongers on October 27, 2005, Michael Graham suggested that certain utility functions could be extracted into a separate Perl extension for more general applicability. This module is the implementation of Michael's suggestion. 🫢

While I was developing those utility functions for ExtUtils::ModuleMaker, I turned to the Perlmonks for help with the problem of determining a suitable value for the user's home directory on Win32 systems. In the Perlmonks discussion threads referred to above, I received helpful suggestions from monks CountZero, Tanktalus, xdg and holli, among others. 🌸

Thanks to Rob Rothenberg for prodding me to expand the SEE ALSO section, and to Adam Kennedy for responding to questions about File::HomeDir.

Thanks to Damyan Ivanov, Xavier Guimard and Gregor Herrman of Debian Perl Group for patches. ✨


Copyright (c) 2005-2026 James E. Keenan. United States. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the LICENSE file included with this module.


πŸ”₯ DISCLAIMER OF WARRANTY πŸ”₯

okay bestie, deep breath, this part is ALL CAPS for a reason and you need to actually read it:

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE ''AS IS'' WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

tl;dr: it's free, it's as-is, and if it breaks something that's on you. no refunds, no drama. πŸ’…

and that's the whole page babes!! πŸŽ€ this little slice of the docs was generated by perl v5.40.1 and dated 2026-01-07, and it's the File::Save::Home(3pm) page β€” go forth and save your files safely, bestie, ily πŸ¦‹πŸ’–

πŸ“¦ where this page comes from