Babacio said:
Note: The author of this message requested that it not be archived. This
message will be removed from Groups in 6 days (Oct 11, 2:38 pm).
Please don't do that. It's rude.
"Paul Lalli"
I think that what the OP means is that $filename =
'/tmp/nonexists/file.txt', for example, and he wants write in it; so
if the file does not exists, the file should be created, but of course
this does not work if the directory '/tmp/nonexists/' does not exist.
Hrm. I can see that interpretation.
May be there is something on CPAN to do that, but it's not a very
difficult thing to write anyway.
I don't know if there's a module on CPAN to do exactly that, but as you
say, it's not overly difficult to write a subroutine that will do it,
especially if we take advantage of a certain module that does exist:
#!/usr/bin/perl
use strict;
use warnings;
use File::Spec;
sub open_or_make(\$$){
my ($fh_ref, $path) = @_;
my ($v, $dirs, $file) = File::Spec->splitpath($path);
my @dirs = File::Spec->splitdir($dirs);
my $dir;
while (my $curdir = shift @dirs){
$dir = $dir ? File::Spec->catdir($dir, $curdir) : $curdir;
-d $dir or mkdir $dir or return undef;
}
open $$fh_ref, '>', $path or return undef;
return 1;
}
my $filename = 'temp/nothere/subdir/file.txt';
open_or_make my $ofh, $filename
or die "Could not open or make $filename: $!\n";
print $ofh "Hello World\n";
close $ofh;
__END__
Paul Lalli