Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a path with all of its subdirectories in one shot in Perl?

Tags:

path

perl

If you have a path to a file (for example, /home/bob/test/foo.txt) where each subdirectory in the path may or may not exist, how can I create the file foo.txt in a way that uses "/home/bob/test/foo.txt" as the only input instead of creating every nonexistent directory in the path one by one and finally creating foo.txt itself?

like image 746
Haiyuan Zhang Avatar asked Aug 25 '09 07:08

Haiyuan Zhang


People also ask

How do I get the directory path in Perl?

The dirname() method in Perl is used to get the directory of the folder name of a file.

How do I assign a path to a variable in Perl?

Making Perl available via the PATH settings on WindowsGo to “Properties” and select the tab “Advanced System settings”. Choose “Environment Variables” and select Path from the list of system variables.


2 Answers

You can use File::Basename and File::Path

 use strict;
 use File::Basename;
 use File::Path qw/make_path/;

 my $file = "/home/bob/test/foo.txt";
 my $dir = dirname($file);
 make_path($dir);
 open my $fh, '>', $file or die "Ouch: $!\n"; # now go do stuff w/file

I didn't add any tests to see if the file already exists but that's pretty easy to add with Perl.

like image 184
seth Avatar answered Nov 01 '22 12:11

seth


Use make_dir from File::Util

   use File::Util;
   my($f) = File::Util->new();
   $f->make_dir('/var/tmp/tempfiles/foo/bar/');

   # optionally specify a creation bitmask to be used in directory creations
   $f->make_dir('/var/tmp/tempfiles/foo/bar/',0755);
like image 20
Nifle Avatar answered Nov 01 '22 12:11

Nifle