KGNickl
asked on
Perl Regular Expression To replace value in text of variable?
See the code below. Basically have a file name, a search value, and a replace value. Everything works, but I don't know regular expressions and how to write one where I have the questions marks that will replace take $file and replace the $search_value within it (if found) with the $replace_value.
Not sure if this can be done in one line w/ a regular expression or if there is another easier way? Thanks! Let me know if anything needs clarification.
Not sure if this can be done in one line w/ a regular expression or if there is another easier way? Thanks! Let me know if anything needs clarification.
my $file = "Test_12354a-bc.doc";
my $search_value = "12354a";
my $replace_value = "replaced";
if($search_value =~ /\b$file\b/){
#True, replace $search_value found in $file with the $replace_value
$file = ?????;
#$file should now be equal to "Test_replaced-bc.doc"
}else{
#False, do nothing
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes, I believe jeromee got want you wanted. I thought $file was the file you wanted to open. Nevermind.
my $file = "Test_12354a-bc.doc";
my $search_value = "12354a";
my $replace_value = "replaced";
open INFILE, $file or die "$!";
my @lines = <INFILE>;
close INFILE;
foreach my $line (@lines)
{
$line =~ s/\b$search_value\b/$repla
}