简体   繁体   English

Perl:从字符串创建目录

[英]Perl: Create directory from strings

Lets suppose I have a base directory /home/user/test/ . 假设我有一个基本目录/home/user/test/ Now, I have two strings a , b which are going to be the folder inside the base directory like /home/user/test/a/b . 现在,我有两个字符串ab ,它们将成为基本目录内的文件夹,如/home/user/test/a/b

Currently what I am doing is: 目前我正在做的是:

use File::Path qw(make_path);

my $path = "$basedir"."/"."a"."/"."b"
make_path("$path");

Now, what am looking for is: 现在,正在寻找的是:

my $dir = "/home/user/test";
my $x = "a";
my $y = "b";

make_path($dir, $x, $y); 

But when I run the above code instead of creating /home/user/test/a/b it creates two separate directory a and b in the current working directory. 但是,当我运行上面的代码而不是创建/home/user/test/a/b它将在当前工作目录中创建两个单独的目录ab

So, what is the correct way to achieve this.? 那么,实现此目标的正确方法是什么?

Here is an easy way to do it: 这是一种简单的方法:

use strict;
use warnings;
use File::Path qw(make_path);    

my $dir = "/home/user/test";
my $x = "a";
my $y = "b";

make_path(join '/',$dir,$x,$y); 

Look up join for more information. 查找join以获取更多信息。

better use Path::Class::Dir 更好地使用Path :: Class :: Dir

use Path::Class qw(dir);  # Export a short constructor

my $dir = dir('foo', 'bar');       # Path::Class::Dir object
my $dir = Path::Class::Dir->new('foo', 'bar');  # Same thing

# Stringifies to 'foo/bar' on Unix, 'foo\bar' on Windows, etc.
print "dir: $dir\n";

see also perldoc Path::Class::Dir or https://metacpan.org/module/Path::Class::Dir 另请参见perldoc Path :: Class :: Dir或https://metacpan.org/module/Path::Class::Dir

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM