0

以下のプログラムが動作しません。変数を使用して単語を新しい単語に置き換えることができません (ユーザー入力)

#Perl program that replace word with given word in the string
$str="\nThe cat is on the tree";
print $str;
print "\nEnter the word that want to replace";
$s1=<>;
print $s1;
print "\nEnter the new word for string";
$s2=<>;
print $s2;
$str=~ tr/quotemeta($s1)/quotemeta($s2)/;
print $str
4

3 に答える 3

3

s///の代わりに演算子を使用する必要がありますtr///

最初のものは「置換」を意味します。これは、(指定されたパターンに一致する) テキストの一部を他のテキストに置き換えるために使用されます。例えば:

my $x = 'cat sat on the wall';
$x =~ s/cat/dog/;
print $x; # dog sat on the wall

2 つ目は「文字変換」を意味します。これは、ある範囲の記号を別の範囲に置き換えるために使用されます。

my $x = 'cat sat on the wall';
$x =~ tr/cat/dog/;
print $x; # dog sog on ghe woll;

ここで起こることは、すべての 'c' が 'd' に置き換えられ、'a' が 'o' になり、't' が 'g' に変換されることです。かっこいいですね。)

Perl ドキュメントのこの部分は、より多くの啓発をもたらします。)

PSそれがスクリプトの主な論理的問題でしたが、他にもいくつかあります。

最初に、入力文字列から末尾記号 ( ) を削除する必要がありchompます。そうしないと、パターンが一致しない可能性があります。

次に、 expression の最初の部分でquotemetacall を\Q...\Esequence に置き換え、2 番目の部分からは完全に削除する必要があります (パターンではなくtexts///に置き換えるため)。

最後に、グローバル変数の代わりにレキシカル変数を使い始めることを強くお勧めします。そして、それらを使用する場所のできるだけ近くで宣言します。

したがって、次のようになります。

# these two directives would bring joy and happiness in your Perl life!
use strict; 
use warnings; 

my $original = "\nThe cat is on the tree";
print $original;

print "\nEnter the word that want to replace: ";
chomp(my $word_to_replace = <>);
print $word_to_replace, "\n";

print "\nEnter the new word for string: ";
chomp(my $replacement = <>);
print $replacement, "\n";

$original =~ s/\Q$word_to_replace\E/$replacement/;
print "The result is:\n$original";
于 2012-09-04T06:41:07.360 に答える
0

次のことを試してください。

$what = 'server'; # The word to be replaced
$with = 'file';   # Replacement
s/(?<=\${)$what(?=[^}]*})/$with/g;
于 2012-09-04T06:43:46.663 に答える
0
#Perl program that replace word with given word in the string
$str="\nThe cat is on the tree";
print $str;
print "\nEnter the word that want to replace";
chomp($s1=<>);
print $s1;
print "\nEnter the new word for string";
chomp($s2=<>);
print $s2;
$str=~ s/\Q$s1\E/\Q$s2\E/;
print $str;
于 2012-09-04T06:44:55.393 に答える