获取“基本名称”来自“glob”
目录路径“/home/PPP/main/windows/agile/cmPvt”的内容为aaa、bbb、ccc、ddd。
代码片段:
use File::Basename;
my $kkLoc = ("/home/PPP/main/windows/agile/cmPvt");
my @kkarray = glob("$kkLoc/*") if (-e $kkLoc);
foreach my $kknum (@kkarray) { ## Here: see below
}
这里:我希望在 @kkarray
中,"aaa", "bbb", "ccc", "ddd"
应该出现,但我得到了整个路径如 "/home/PPP/main/windows/agile/cmPvt/aaa", "/home/PPP/main/windows/agile/cmPvt/bbb",....
另外,我尝试过,foreach my $kknum (basename "@kkarray") { }
,但不起作用。
在执行 glob() 时如何从完整路径获取“基本名称”?
注意:由于某种原因,我无法在执行 glob
命令之前对路径执行 chdir
操作。
Directory path "/home/PPP/main/windows/agile/cmPvt" has aaa, bbb, ccc, ddd as its contents.
Code Snippet:
use File::Basename;
my $kkLoc = ("/home/PPP/main/windows/agile/cmPvt");
my @kkarray = glob("$kkLoc/*") if (-e $kkLoc);
foreach my $kknum (@kkarray) { ## Here: see below
}
Here: here I want that in @kkarray
, "aaa", "bbb", "ccc", "ddd"
shall come, but I am getting the whole path like "/home/PPP/main/windows/agile/cmPvt/aaa", "/home/PPP/main/windows/agile/cmPvt/bbb",....
Also, I tried, foreach my $kknum (basename "@kkarray") { }
, but not working.
How can I get the "basename" from the full path while doing glob()
?
Note: I can't do chdir
to the path before executing glob
command due to a reason.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您尝试使用带有插值数组的字符串作为
basename
的参数。那是错误的。您应该采用单独的路径,而不是所有连接在一起的路径。它在文档中说明了应该如何使用
basename
功能:您应该注意,通过从 glob 中删除完整路径,如果您也无法
chdir
到文件的位置,则您将无法访问这些文件,就像您所说的“由于某种原因”无法执行操作一样。所以这整个练习对你来说可能毫无意义。您可能想看看
File::Find
,它确实类似的事情,递归地,自动地允许您选择基本名称或全名。就像一个多合一包装。You tried to use a string with the interpolated array as argument to
basename
. That is wrong. You should take the individual paths, not all the paths concatenated together.It says in the documentation how you should use the
basename
function:You should note that by removing the full paths from the glob, that you cannot access the files if you cannot also
chdir
to their location, like you said you could not do "for a reason". So this whole exercise might be quite pointless for you.You might like to look at
File::Find
which does a similar thing, recursively, and automatically allows you to select basename or full name. Like an all in one package.您可以使用 map 在数组的每个元素上调用
basename
:如果需要,这会将完整路径保留在数组变量中。
如果您不想在数组变量中使用完整路径,则可以在填充数组时使用
map
:You can use map to call
basename
on each element of the array:This keeps the full path in the array variable, if that is desired.
If you never want the full path in the array variable, you can use
map
when you populate the array:如果您只对该目录中的文件名感兴趣,那么只需直接读取该目录:
If you're only ever interested in the filenames within that directory, then just read the directory directly: