如何在一系列逐渐编号的文件中创建下一个文件或文件夹?
抱歉标题不好,但这是我能做的最好的了! :D
我有一个脚本,每次调用指定函数时都会创建一个新项目。
每个项目必须存储在其自己的文件夹中,并带有项目名称。但是,如果您不指定名称,脚本只会将其命名为“new projectX”,其中 X 是一个渐进数字。
随着时间的推移,用户可以重命名文件夹或删除一些文件夹,因此每次脚本运行时,它都会检查可用的最小数量(未被其他文件夹使用)并创建相关文件夹。
现在我设法制作了一个程序,我认为该程序可以按需要工作,但由于我对语言缺乏经验,我想听听您的意见是否可以,或者是否存在我无法发现的错误。
while ( defined( $file = readdir $projects_dir ) )
{
# check for files whose name start with "new project"
if ( $file =~ m/^new project/i )
{
push( @files, $file );
}
}
# remove letters from filenames, only the number is left
foreach $file ( @files )
{
$file =~ s/[a-z]//ig;
}
@files = sort { $a <=> $b } @files;
# find the smallest number available
my $smallest_number = 0;
foreach $file ( @files )
{
if ( $smallest_number != $file )
{
last;
}
$smallest_number += 1;
}
print "Smallest number is $smallest_number";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是解决此类问题的基本方法:
如果您愿意使用与 Perl 的 字符串自动递增功能,可以进一步简化代码,不再需要
$n
。例如,newproject000
。Here's a basic approach for this sort of problem:
If you're willing to use a naming pattern that plays nicely with Perl's string auto-increment feature, you can simplify the code further, eliminating the need for
$n
. For example,newproject000
.我想我会使用类似的东西:
测试代码:
I think I would use something like:
Test code:
试试这个:
Try this:
本身没有什么问题,但是要实现一个目标(获取目录的最小索引)需要编写大量代码。
一个核心模块、几个子模块和一些 Schwartzian 变换将使代码更加灵活:
Nothing wrong per se, but that's an awful lot of code to achieve a single objective (get the minimum index of directories.
A core module, couple of subs and few Schwartzian transforms will make the code more flexible: