** ' * *'でマークされたフォローアップの質問があります**
私は Perl コードを書くように頼まれました。これは、everyを{
with{function(<counter>)
に置き換え、すべての置換でカウンターが 1 大きくなるはずです。たとえば、1 回目の置換は{
will {function(0)
、2 回目の置換は{
will{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 ファイルごとに行ごとに移動し、この行に '{ が含まれているかどうかを確認することです。 '。存在する場合、プログラムは '{' があるかどうかをチェックせず、置換を行いません。存在しない場合、プログラムは '{' を '{function();' に置き換えます。
残念ながら、このコードは機能しません。私はそれを一日中機能させようとしているのに、まだうまくいかないと言うのは恥ずかしい. 助けていただければ幸いです。
ありがとうございました!!