Perl rename命令在内部是如何工作的

cl25kdpy  于 2023-10-24  发布在  Perl
关注(0)|答案(1)|浏览(147)

rename是一个用于重命名多个文件的Perl脚本。我想知道rename是如何完成它的工作的,它似乎都陷入了这一行(如果它正在重命名一个文件):
https://metacpan.org/dist/File-Rename/source/lib/File/Rename.pm#L37
$sub->() for ($file);
如果从命令行传递的替换命令是's/\.bak$//',请问我的理解是正确的吗?

$ perl
$code = 's/\.bak$//'
$eval = eval "sub { $code }"
$sub = $eval
$sub->() for ('a.b.c.bak')
__END__
9jyewag0

9jyewag01#

实际的重命名是在下面完成的:

CORE::rename($was,$_)

您发布的是基于用户提供的代码计算新名称的代码的近似值。更好的近似值:

my $code = 's/\.bak$//'
my $sub = eval "sub { $code }"

my @args = 'a.b.c.bak'; 
for (@args) {           # Aliases `$_` to the array element.
   my $was = $_;
   $sub->();            # Probably changes `$_`.

   say "$was => $_";    # The rename would happen here.
}

如果我们把潜艇连上,

my @args = 'a.b.c.bak'; 
for (@args) {           # Aliases `$_` to the array element.
   my $was = $_;
   s/\.bak$//;          # Changes `$_`.

   say "$was => $_";    # The rename would happen here.
}

相关问题