I am trying to prompt user to type input and replace certain attribute in a file with the input. This is not working. abc.txt contain line "NA" and I wish to replace with "user_input". Any help? Thanks
use strict;
use warnings;
my $x = "<process>NA</process>";
print "Please specify process used\n";
my $process = <STDIN>;
chomp $process;
open(XML, "<", "abc.txt") or die "Couldn't open file, $!";
while(<XML>){
s/<process>NA</process>/<process>$process</process>/g;
}
@Blurman, if you are using some sort of /bin/sh you use the inplace option of perl with this the one-liner:
echo -n 'process ? ';read p; perl -pi -e "s,<process>[^<]*</process>,<process>$p</process>,g" abc.txt
oh BTW, I changed NA
w/ [^<]*
to allow multiple consecutive runs;)
+Michel
The main part of your code is here:
open(XML, "<", "abc.txt") or die "Couldn't open file, $!";
while(<XML>){
s/<process>NA</process>/<process>$process</process>/g;
}
There are two main problems here that will stop your code doing what you want.
You have /
characters in side the match pattern and replacement string of your substitution operator. This means your code won't even compile. If you have /
characters in your data, then the best option is to use a different character as the delimiter for the substitution operator.
s|<process>NA</process>|<process>$process</process>|g;
You change your data (which is stored in $_
) but then you do nothing with the changed version. You need to write the changed version of the data back to a file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.