perl中的几个替换

时间:2017-06-02 16:29:19

标签: perl

如何使用Perl进行两次替换?

我使用以下代码。我使用两次s代替......我希望所有人都能用更少的线...

        (my $newName = $grib) =~ s/:00:00.grb//;
        rename $grib, $newName;

        (my $newName1 = $newName)  =~ s/d01/d02/g;
        rename $newName, $newName1;

1 个答案:

答案 0 :(得分:7)

根据要求:

(my $newName = $grib) =~ s/:00:00.grb//; rename $grib, $newName; (my $newName1 = $newName)  =~ s/d01/d02/g; rename $newName, $newName1;

但那是愚蠢的。也没有理由把所有东西都塞进一行。相反,致力于生成高质量的可读代码。对于初学者来说,一旦做到就停止重命名两次!

my $newName = $grib;
$newName =~ s/:00:00.grb//;
$newName =~ s/d01/d02/g;
rename($grib, $newName)
   or die("Can't rename \"$grib\" to \"$newName\": $!\n");

对于5.14+,可以将其简化为以下内容:

my $newName = $grib =~ s/:00:00.grb//r =~ s/d01/d02/gr;
rename($grib, $newName)
   or die("Can't rename \"$grib\" to \"$newName\": $!\n");