tilde (~) directories in Perl

directory, perl

Solution

The tilde is interpreted by the shell to mean your home directory.

Hence Perl's `-d` operator sees something different (a file/directory called `~`) to your shell invocation `'mkdir ~/whatever'` (which expands `~` to mean `/home/user`).

I would try to use exclusively Perl functions to perform your operations. You'll avoid spawning new processes and your file access will be performed in a consistent fashion.

Note Perl's mkdir built-in function. Note also the File::Glob module which does perform expansion of the ~ character (perhaps useful if you have users entering directory names manually)

Problem

I found a slight misbehaviour in my Perl script when I create and check for the existence of directories with a tilde sign, which doesn't happen if I use a full `/home/user` path. When I run this script for the first time, it creates the new directory. When I run it the second time, it doesn't recognise the existence of the directory, and tries to create it a second time: ``` #!/usr/bin/perl use strict; my $outdir = '~/test'; my $cmd = "mkdir $outdir"; unless (-d $outdir) { 0 == system($cmd) or die "Error creating outdir $outdir\n $?"; } 1; [~] $ rm test/ -rf [~] $ perl dir.pl [~] $ perl dir.pl mkdir: cannot create directory `/home/avilella/test': File exists Error creating outdir ~/test 256 at dir.pl line 7. ``` How can I reliably deal with directories that use the tilde `~` sign in Perl?

Original source