SPUG: Yet another silly question

Yitzchak Scott-Thoennes sthoenna at efn.org
Mon Jan 21 23:25:07 CST 2002

In article <a05101206b8721ee64c05@[]>,
Jason Lamport <jason at strangelight.com> wrote:
>At 8:10 am -0800 1/21/02, Pommert, Daniel wrote:
>>I have found that mkpath will check to see if the directory is there before
>>it tries to create it.  So, checking is not necessary when using mkpath.
>Is this behaviour in the documentation for File::Path, or is this 
>simply something you've observed?  I personally consider it poor 
>programming practice to rely on undocumented behaviour, even in 
>trivial cases such as this. (And even if it is part of the formal 
>spec, an extra check rarely hurts.)

I have File::Path version 1.0404 here.
It does indeed skip directories that already exist.  It returns a list
of directories created (including intermediates).  In scalar context,
this is a count of directories created.  So if you say mkpath("$base/$dir"...)
and $base/$dir already exists it returns 0.  So in the suggested code below,
the die is triggered.  Worse yet, since no system error actually occured,
the value of $! is meaningless.  Indeed, an extra check rarely hurts.

>>So, the code below would better be written:
>>#!/usr/bin/perl -w
>>$dir = "some/directory/path";
>>$base = "/usr/people/moonbeam";
>>use File::Path;
>>if ( ! -f "$base/$dir" ) {
>>     mkpath("$base/$dir", 0, 0755 ) or
>>         die "Cannot make $dir/$base - $!\n";
>>else {
>>     print STDERR, "$base/$dir already exists as a file!\n";



I'm also not sure what the point is of printing a warning (but not via
warn) if $base/$dir already exists as a file but dying if if any of
the intermediates exist as a file.  (BTW, mkpath already does a die if
a mkdir fails.  The only case I see that *will* hit the die above is
if the directory already exists.)

You might try something like this:
my $makeme = "$base/$dir";  # portably, use = File::Spec::->catfile($base,$dir)
eval { mkpath($makeme,0,0755) };
warn "Error making path $makeme: ", ($@ || "race condition") unless -d $makeme;

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://zipcon.net/spug/

More information about the spug-list mailing list