vimal9844
vimal9844

Reputation: 1

How to pass variable to regular expression in PERL

Following program is not working. I am not able to replace word with new word using variable (User input)

#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

Upvotes: 0

Views: 1913

Answers (3)

raina77ow
raina77ow

Reputation: 106385

You need to use s/// operator instead of tr///.

The first one means 'substitution': it is used to replace some parts of text (matched by the given pattern) with some other text. For example:

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

The second one means 'transliteration': it is used to replace some range of symbols with another range.

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

What happens here is all 'c' were replaced by 'd', 'a' become 'o' and 't' transformed into 'g'. Pretty cool, right. )

This part of Perl documentation would bring more enlightenment. )

P.S. That was the main logical problem with your script, but there are several others.

First, you need to remove the endline symbols (chomp) from the input strings: otherwise the pattern will probably never match.

Second, you should replace quotemeta call with \Q...\E sequence in the first part of s/// expression, but drop it altogether from the second (as we replace with text, not a pattern).

Finally, I strongly suggest starting using lexical variables instead of global ones - and declaring them as close to their place of usage as possible.

So it becomes close to this:

# 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";

Upvotes: 3

BSen
BSen

Reputation: 187

#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;

Upvotes: 0

Shail
Shail

Reputation: 1575

Try the following:

$what = 'server'; # The word to be replaced
$with = 'file';   # Replacement
s/(?<=\${)$what(?=[^}]*})/$with/g;

Upvotes: 0

Related Questions