[英]Search and replace in file in Perl?
Following from this example here on another SO question. 从此示例开始 ,接着是另一个SO问题。
I added the following code to my basic perl script. 我在基本的perl脚本中添加了以下代码。
#!/usr/bin/perl
$^I = '.bak'; # create a backup copy
while (<>)
{
s/NewProdId/$ARGV[1]/g; # do the replacement
s/PortId/$ARGV[2]/g; # do the replacement
s/AssemblyId/$ARGV[3]/g; # do the replacement
print; # print to the modified file
}
However when I call the perl script with more than one argument, it breaks. 但是,当我用一个以上的参数调用perl脚本时,它就会中断。 It appears to e mistaking my other argument for a filename for it to open.
看来我误以为其他参数打开了文件名。
Can't open 1-THU-71: No such file or directory at ./process.pl line 11, <> line 37.
无法打开1-THU-71:./process.pl第11行,<>行37中没有此类文件或目录。
Can't open 1-5XJ0DF: No such file or directory at ./process.pl line 11, <> line 37.
无法打开1-5XJ0DF:./process.pl第11行,<>行37中没有此类文件或目录。
Can't open 1-3F0MB9: No such file or directory at ./process.pl line 11, <> line 37.
无法打开1-3F0MB9:./process.pl第11行,<>第37行中没有此类文件或目录。
My bash script call is as such: 我的bash脚本调用是这样的:
./process.pl "test.txt" $values
What am I doing wrong here? 我在这里做错了什么?
The diamond operator <>
tries to open all the files mentioned in the arguments. 菱形运算符
<>
尝试打开参数中提到的所有文件。 You should remove elements from @ARGV
which are not file names: 您应该从
@ARGV
中删除不是文件名的元素:
my @ar = @ARGV;
@ARGV = shift @ARGV;
while (<>)
{
s/NewProdId/$ar[1]/g; # do the replacement
s/PortId/$ar[2]/g; # do the replacement
s/AssemblyId/$ar[3]/g; # do the replacement
print; # print to the modified file
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.