免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 7697 | 回复: 5
打印 上一主题 下一主题

perl打开不存在的文件路径时,怎么自动创建目录? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-10-13 15:23 |只看该作者 |倒序浏览
有什么方法?
比如
open FILE,">dir1\\dir2\\file1" or die "$!";
当前目录下没有dir1,它就抛:No such file or directory at test.pl line 39.

论坛徽章:
0
2 [报告]
发表于 2011-10-13 16:27 |只看该作者
看来没简单现成的方法,自己写一个:
sub createFilePath{
        my $filePath = shift;
        my $separator = shift || "\\";
        my $pos = 0;
        while (($pos = index($filePath, $separator, $pos)) > -1) {               
                my $path = substr $filePath,0,$pos;               
                unless (-e $path) {
                        mkdir $path or die $!;
                } elsif( !(-d $path)) {
                        die "$path is not a directory."
                } else {
                }
                $pos++;
        }
}

论坛徽章:
0
3 [报告]
发表于 2011-10-13 16:35 |只看该作者
使用 File::Util的make_dir().

Syntax: make_dir( [new directory name] , [bitmask], [--opts] )

论坛徽章:
0
4 [报告]
发表于 2011-10-13 21:08 |只看该作者
use File:ath qw<make_path>;
  1. use File::Path qw(make_path remove_tree);

  2.   make_path('foo/bar/baz', '/zug/zwang');
  3.   make_path('foo/bar/baz', '/zug/zwang', {
  4.       verbose => 1,
  5.       mode => 0711,
  6.   });

  7.   remove_tree('foo/bar/baz', '/zug/zwang');
  8.   remove_tree('foo/bar/baz', '/zug/zwang', {
  9.       verbose => 1,
  10.       error  => \my $err_list,
  11.   });

  12.   # legacy (interface promoted before v2.00)
  13.   mkpath('/foo/bar/baz');
  14.   mkpath('/foo/bar/baz', 1, 0711);
  15.   mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
  16.   rmtree('foo/bar/baz', 1, 1);
  17.   rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
复制代码

论坛徽章:
0
5 [报告]
发表于 2011-10-13 21:09 |只看该作者
可以直接创建多层子目录

论坛徽章:
0
6 [报告]
发表于 2011-10-18 20:29 |只看该作者
system('mkdir -p **')
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP