gpt4 book ai didi

perl - 如何在 perl 脚本中删除扩展名

转载 作者:行者123 更新时间:2023-12-01 23:57:41 25 4
gpt4 key购买 nike

一个愚蠢的问题,但它让我发疯!我有一个脚本可以删除 bvh 文件中的“胖”数据。 (Biovision Action 捕捉文件..)。工作正常,但它创建了一个双重扩展......(名称.bvh.bvh)我只需要一个扩展名(*.bvh,不是 *.bvh.bvh!!!)这是代码:

@files = <*.bvh>;
foreach $file (@files) {
open (OLD, $file) || die "Couldn´t open $file: $!\n";
open (NEW, ">$file.bvh") || die "Couldn´t open $file.bvh: $!\n";
while (<OLD>) {
$line = $_;
if (/Normal/) { while (<OLD>) { last if /}/; } $line => ""; }
if (/normalIndex/) { while(<OLD>) { last if /[]]/; } $line = ""; }
$line =~ s/[-+]?[0-9]\.[0-9]+e[+-][0-9]+/0/g;
$line =~ s/([-+]?[0-9]+\.[0-9]{2})[0-9]+/$1/g;
$line =~ s/0\.00/0/g;
$line =~ s/[ ]+/ /g;
$line =~ s/[\t]+/ /g;
$line =~ s/^ //g;
print NEW $line;

}
close OLD;
unlink ($file);
close NEW;
}

有什么帮助吗?谢谢!

最佳答案

@files = <*.bvh>;

这为您提供了具有 .bvh 扩展名的文件列表。所以它最终会包含如下内容:

('foo.bvh', 'bar.bvh', 'baz.bvh')

然后用这段代码遍历数组:

foreach $file (@files) {
...
}

每次循环,$file 都将包含您数组中的一个值。例如,在第一次迭代中,$file 将包含 foo.bvh

然后打开输入和输出文件:

open  (OLD, $file) || die "Couldn´t open $file: $!\n";
open (NEW, ">$file.bvh") || die "Couldn´t open $file.bvh: $!\n";

由于 $file 包含 foo.bvh,您的新文件(使用名称 "$file.bvh" 创建)将被称为 foo.bvh.bvh

天真的解决方法是从 open() 语句中删除 .bvh:

# DON'T DO THIS
open (OLD, $file) || die "Couldn´t open $file: $!\n";
open (NEW, ">$file") || die "Couldn´t open $file.bvh: $!\n";

这将不起作用,因为您的旧文件和新文件现在将具有相同的名称,并且当您打开新文件进行写入时,它将截断文件并删除所有输入数据。

您有时需要重命名文件。最简单的方法是保留现有文件名,并在处理完每个文件后,将其重命名为原始名称。

# And then at the end of your loop
# Note that as you're copying the new file over the old one,
# there's no need to delete the old one.
close OLD;
close NEW;
rename("$file.bvh", $file);

关于perl - 如何在 perl 脚本中删除扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62423290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com