PERL语言 几个问题请高手指点 1
Write a very short program typereplace.pl to rename the type for files in your current directory, e.g., from .txt to .t. Start by listing all the files in your current directory (let's say four in a row, separated by a tab), then ask for the change, and finally print out the list of modified files, as shown here:
comp315@turing> typereplace.pl
Files in your working directory:
a.pl b.pl c.pl dd
d.pl e.pl f.pl g.pl
hello1.pl hello.pl here.pl i1.pl
i2.pl i3.pl parseURL persoane
q1.t.txt q1.txt q1.txt.txt q4.txt
question_02.txt testPattern tilde1.pl tilde.pl
typereplace.pl
Please enter the old type of files: txt
Please enter the new type of files: t
We'll do the replacement: txt--->t
q1.t.txt--->q1.t.t
q1.txt--->q1.t
q1.txt.txt--->q1.txt.t
q4.txt--->q4.t
question_02.txt--->question_02.t
参考答案: 可以在原程序上改 也可以自己编译程序
#!/usr/bin/perl
use warnings;
use strict;
my @files = glob "*";
print "Files in your working directory:\n";
for (my $i=0; $i <= $#files; $i++) {
if ($i%4==0 && $i != 0){
print "\n";
}
print "$files[$i]\t";
}
print "\nPlease enter the old type of files:";
my $txt =<STDIN>;
chomp($txt);
print "Please enter the new type of files:";
my $t =<STDIN>;
chomp($t);
print "We'll do the replacement: $txt--->$t\n";
for(my $i=0; $i <= $#files; $i++){
if($files[$i] =~ m/${txt}/){
my $filenew = substr($files[$i],
0,((length($files[$i]))-(length($txt)))).$t;
print "$files[$i] ---> $filenew\n";
rename($files[$i], $filenew);
[解决办法]
前面都ok,最后一个for循环也可以用正则表达式来替换:
for(my $i=0; $i <= $#files; $i++){ if((my $filenew = $files[$i]) =~ s/\.$txt$/\.$t/) { print "$files[$i] ---> $filenew\n"; rename($files[$i], $filenew); }}
[解决办法]
有个问题,要替换的后缀名应该是在名字最后出现的,你匹配的时候没有做这个限定,这样只要名字中出现txt,你就给换了,与要求不符
$txt = '.'.$txt; #前面加上点
$t = '.'.$t;
if($files[$i] =~ m/${txt}$/){ # 限定末尾匹配
$filenew = $files[$i];
$filenew =~ s/${txt}$/${t}/; #用正则替换
}