私はGetopsを使用してユーザー入力を受け取る小さなプログラムを書いています。それに基づいて、プログラムはパターンをテキストと照合するか、一致したものをテキストに置き換えます。
私が抱えている問題は、置換部分を機能させることができないということです。マニュアルページのqr//エントリを見ています:http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operatorsしかし、私はそれで運がありません。この場合、ドキュメントとまったく同じようにコードをモデル化しようとしました。一致パターンをコンパイルし、それを置換に置き換えます。
誰かが私がどこで間違っているのか指摘できますか?(セキュリティについてはあまり心配しないでください。これは個人的な使用のためのほんの少しのスクリプトです)
これが私が見ているものです:
if($options{r}){
my $pattern = $options{r};
print "\nEnter Replacement text: ";
my $rep_text = <STDIN>;
#variable grab, add flags to pattern if they exist.
$pattern .= 'g' if $options{g};
$pattern .= 'i' if $options{i};
$pattern .= 's' if $options{s};
#compile that stuff
my $compd_pattern = qr"$pattern" or die $@;
print $compd_pattern; #debugging
print "Please enter the text you wish to run the pattern on: ";
my $text = <STDIN>;
chomp $text;
#do work and display
if($text =~ s/$compd_pattern/$rep_text/){ #if the text matched or whatever
print $text;
}
else{
print "$compd_pattern on \n\t{$text} Failed. ";
}
} #end R FLAG
-r "/ matt /" -iを指定して実行し、置換テキスト'matthew'をテキスト'matt'に入力すると、失敗します。どうしてこれなの?
編集:
答えてくれてありがとう!それは本当にとても役に立ちました。私はあなたの両方の提案を問題の実用的な解決策にまとめました。/gフラグの処理方法を少し変える必要があります。作業サンプルは次のとおりです。
if($options{r}){
my $pattern = $options{r};
print "\nEnter Replacement text: ";
my $rep_text = <STDIN>;
chomp $rep_text;
#variable grab, add flags to pattern if they exist.
my $pattern_flags .= 'i' if $options{i};
$pattern_flags .= 's' if $options{s};
print "Please enter the text you wish to run the pattern on: ";
my $text = <STDIN>;
chomp $text;
#do work and display
if($options{g}){
if($text =~ s/(?$pattern_flags:$pattern)/$rep_text/g){ #if the text matched or whatever (with the g flag)
print $text;
}
else{
print "$pattern on \n\t{$text} Failed. ";
}
}
else{
if($text =~ s/(?$pattern_flags:$pattern)/$rep_text/){ #if the text matched or whatever
print $text;
}
else{
print "$pattern on \n\t{$text} Failed. ";
}
}
} #end R FLAG