【发布时间】:2014-06-05 04:05:49
【问题描述】:
我正在尝试制作一个替换目录中所有文件中的字符串的程序。问题是我需要让它只有在句子的开头或结尾,或两者兼而有之时才可以更改。这是我目前所拥有的:
use strict;
use warnings;
use File::Find; #This lets us use the find() function, similar to 'find' in Unix
# -- which is especially helpful for searching recursively.
print "Which directory do you want to use?\n"; #Ask what directory to use
my $dir = readline STDIN;
chomp $dir; #Used for eliminating the newline character '\n'
print "What String would you like to search for?\n"; #Ask for what String to search for.
my $search = readline STDIN;
chomp $search;
print "What String would you like to replace it with?\n"; #Ask for what to replace it with.
my $replace = readline STDIN;
chomp $replace;
print "Would you like to replace $search if it is at the beginning of the sentence? (y/n) \n";
my $beg = readline STDIN;
chomp $beg;
print "Would you like to replace $search if it is at the end of the sentence? (y/n) \n";
my $end = readline STDIN;
chomp $end;
find(\&txtrep, $dir); #This function lets us loop through each file in the directory
sub txtrep {
if ( -f and /.txt$/) { # Proceeds only if it is a regular .txt file
my $file = $_; # Set the name of the file, using special Perl variable
open (FILE , $file);
my @lines = <FILE>; #Puts the file into an array and separates sentences
my @lines2 = split(".", @lines);
close FILE;
if ($beg eq "y") {
foreach my $slot (@lines2) {
$slot =~ s/^$search/$replace/gi;
}
}
if ($end eq "y") {
foreach my $slot (@lines2) {
$slot =~ s/$search$/$replace/gi;
}
}
open (FILE, ">$file");
print FILE @lines2;
close FILE;
}
}
在我运行这个之后,它只是删除了文件中的所有内容,我不知道更改字符串@句子开头和结尾的语法是否正确。请让我知道我做错了什么!谢谢!
【问题讨论】: