**我有一个标有“* *”的后续问题**如何更改目录使用Perl
我是在所有文件字符的所有出现(和子目录)要求编写Perl代码,将{
替换为{function(<counter>)
,并且在每次更换时计数器应该增大1.例如第一次更换的{
将{function(0)
, 第二更换{
将{function(1)
等 它该做的每一个*.c
和*.h
文件替换包括子文件夹的文件夹。
我写了这个代码:
#!/usr/bin/perl
use Tie::File;
use File::Find;
$counter = 0;
$flag = 1;
@directories_to_search = 'd:\testing perl';
@newString = '{ function('.$counter.')';
$refChar = "{";
finddepth(\&fileMode, @directories_to_search);
sub fileMode
{
my @files = <*[ch]>; # get all files ending in .c or .h
foreach $file (@files) # go through all the .c and .h flies in the directory
{
if (-f $file) # check if it is a file or dir
{
my @lines;
# copy each line from the text file to the string @lines and add a function call after every '{' '
tie @lines, 'Tie::File', $file or die "Can't read file: $!\n";
foreach (@lines)
{
if (s/{/@newString/g)
{
$counter++;
@newString = '{function('.$counter.')';
}
untie @lines; # free @lines
}
}
}
}
代码搜索目录d:\testing Perl
和不更换而是获得 {function(<number>)
我得到{function(number1) function(number3) function(number5) function(number7)
例如用于第一替换我得到 {function(0) function(2) function(4) function(6)
,我希望得到{function(0)
我真的不知道我的代码有什么问题。
一个awk解决方案或任何其他Perl解决方案也将是伟大的!
*我有一个跟进的问题。 现在我想让我的Perl程序在除了行之外的所有文件中执行相同的替换,当在同一行中有'{'
和'}'时。所以我用这种方式修改了代码。
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
use File::Find;
my $dir = "C:/test dir";
# fill up our argument list with file names:
find(sub { if (-f && /\.[hc]$/) { push @ARGV, $File::Find::name } }, $dir);
$^I = ".bak"; # supply backup string to enable in-place edit
my $counter = 0;
# now process our files
#foreach $filename (@ARGV)
while (<>)
{
my @lines;
# copy each line from the text file to the string @lines and add a function call after every '{' '
tie @lines, 'Tie::File', $ARGV or die "Can't read file: $!\n";
#$_='{function(' . $counter++ . ')';
foreach (@lines)
{
if (!(index (@lines,'}')!= -1)) # if there is a '}' in the same line don't add the macro
{
s/{/'{function(' . $counter++ . ')'/ge;
print;
}
}
untie @lines; # free @lines
}
什么,我试图做的是要经过@ARGV中的所有文件,我在我的目录和子目录和每个的* .c或* .h文件中找到我想要通过线走线和检查这一行是否包含“{”。如果是这样,程序将不检查是否有'{'并且不会进行替换,如果程序不会用'{'替换'{'();''
不幸的是,这段代码不起作用。 我很惭愧地说,我试图让它工作一整天,但仍然没有去。 我真的很感谢一些帮助。
谢谢!
为什么要使用这两个文件::查找*和*一个水珠找到文件?你知道,这两次做同样的工作。 – TLP
我没有看到你将字符串“数字”添加到代码中的任何东西。你确定你的意思是你在输出中看到“number1”,“number3”等吗? – TLP