Perl:获取文件的大小写敏感名称

4

我有一个Perl脚本,需要在任何平台上工作(Windows,Mac,Linux等)。 其中一部分功能是重命名文件,但我不希望它覆盖现有的文件。 假设脚本被称为“ my_rename”,并且它采用与“ rename”函数相同的参数,并且用户执行此命令:

my_rename test.txt test.TXT

如果-e“ test.txt”和-e“ test.TXT”都返回true,则会出现问题。 在以下条件下,我想如何处理此情况:

情况1:在区分大小写的文件系统上:

  • 报错“test.TXT”已存在并中止操作

情况2:在不区分大小写的文件系统上,当现有文件名的实际大小写为“test.TXT”时:

  • 发出警告,文件名保持不变

情况3:在不区分大小写的文件系统上,当现有文件名的实际大小写不是“test.TXT”时:

  • 将文件重命名为“test.TXT”

由于该脚本必须是可移植的,因此不能依赖于系统相关的功能或实用程序。

任何建议都将不胜感激。

  • Phil
1个回答

4
我在这里的做法是跳过-e,直接使用readdir
在输入时,您需要知道与readdir匹配的不区分大小写的匹配数量。
if (! -e $input)
{
  die "No such file: $input";
}

my $input_case_insensitive_matches = () = use_readdir_to_find($input);
my $output_is_case_match = use_readdir_to_find($output);

if ($input_case_insensitive_matches > 1 && $output_is_case_match)
{
  # case sensitive filesystem, target exists, as does the input file
  die "$output already exists";
}

if ($output_is_case_match)
{
  # case insensitive filesystem, no change required
  warn "$input is already $output";
}
else
{
  # case can be changed
  rename $input, $output;
}

可能需要进行一些调试。


谢谢您的建议,但您似乎已经假定文件系统是不区分大小写的。我不能做出这样的假设。此外,在包含Unicode字符的文件名上,Windows中的readdir存在严重问题。 - PhilHarvey
我不认为我在做前一个假设,但是我对Unicode方面并不了解。 - Tanktalus
啊,我现在明白了。在区分大小写的系统上,当两个文件都存在时,不区分大小写的readdir搜索将会找到多个文件。明白了。但这仍然存在Unicode的问题。 - PhilHarvey
我感到困惑,因为在使用 use_readdir_to_find() 查找 $input 时必须不区分大小写,但对于 $output 则需要区分大小写。 - PhilHarvey
2
它在列表上下文中返回所有不区分大小写的匹配项,在标量上下文中返回精确的区分大小写的匹配项(或无匹配项)。或者使用不同的函数,随便怎么做。 - Tanktalus
啊,聪明。谢谢你的想法。 - PhilHarvey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接