Perl 在脚本中进行就地编辑(而不是单行) [英] Perl in place editing within a script (rather than one liner)
问题描述
所以,我习惯于 perl -i
使用 perl,就像我使用 sed
和就地编辑一样.
So, I'm used to the perl -i
to use perl as I would sed
and in place edit.
perlvar
中 $^I
的文档:
$^I就地编辑扩展的当前值.使用 undef 禁用就地编辑.
$^I The current value of the inplace-edit extension. Use undef to disable inplace editing.
好的.所以这意味着我可能会在脚本中进行就地"编辑?
OK. So this implies that I can perhaps mess around with 'in place' editing in a script?
我遇到的问题是:
如果我跑:
perl -pi -e 's/^/fish/' test_file
然后解析它:
BEGIN { $^I = ""; }
LINE: while (defined($_ = <ARGV>)) {
s/^/fish/;
}
continue {
die "-p destination: $!\n" unless print $_;
}
现在 - 如果我想在脚本中使用 $^I
,请说:
Now - if I were to want to use $^I
within a script, say to:
foreach my $file ( glob "*.csv" ) {
#inplace edit these files - maybe using Text::CSV to manipulate?
}
我如何启用"这种情况?这是更改 $_
(如 s/something/somethingelse/
默认情况下所做的)并让 perl 隐式打印它的问题吗?还是有其他事情发生?
How do I 'enable' this to happen? Is it a question of changing $_
(as s/something/somethingelse/
does by default) and letting perl implicitly print it? Or is there something else going on?
我的主要问题是 - 我可以进行应用 CSV 转换(或 XML 调整或类似操作)的就地编辑"吗?
My major question is - can I do an 'in place edit' that applies a CSV transform (or XML tweak, or similar).
我很感激我可以打开单独的文件句柄、读取/打印等.我想知道是否还有其他方法.(即使它只是在特定情况下有用).
I appreciate I can open separate file handles, read/print etc. I was wondering if there was another way. (even if it is only situationally useful).
推荐答案
由 -i
命令行选项或通过设置 $^ 启用的就地编辑行为I
仅适用于 ARGV
文件句柄.这意味着文件必须在命令行中命名或 @ARGV
必须在程序中设置
The edit-in-place behaviour that is enabled by the -i
command-line option or by setting $^I
works only on the ARGV
file handle. That means the files must either be named on the command line or @ARGV
must be set up within the program
此程序会将所有 CSV 文件中的所有小写字母更改为大写字母.请注意,我已将 $^I
设置为非空字符串,建议您在测试时这样做,以便保留原始数据文件
This program will change all lower-case letters to upper-case in all CSV files. Note that I have set $^I
to a non-null string, which is advisable while you are testing so that your original data files are retained
use strict;
use warnings;
our $^I = '.bak';
while ( my $file = glob '*.csv' ) {
print "Processing $file\n";
our @ARGV = ($file);
while ( <ARGV> ) {
tr/a-z/A-Z/;
print;
}
}
这篇关于Perl 在脚本中进行就地编辑(而不是单行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!