我想在tex文档上运行perl脚本,但不想在序言上运行。如何将它的效果限制在某个模式下的文件部分(例如^\\begin\{document\}$)?这是一个脚本:
# Insert the macro \gr{} around Greek passages.
#!/usr/bin/env perl
use strict;
use warnings;
use Encode;
my $L = qr/[^A-Za-z]/;
my $g = qr/\p{Greek}/;
local $/; # slurp
$_ = decode('utf-8', <>);
# Remove already existing instances.
s/\\gr
( # 1
{
( # 2
(?: \\. # 3. escaped chars
| [^{}]
| (?1) # recur to 1
)*
)
}
)
/$2/xg;
# Insert new.
s/(
[([]* # begin with puncuation?
$g # Greek;
($L|\\\w+)* # contain any non-Latin char or cmd;
$g # end with Greek
[)\]]* # and puncuation?
)
/\\gr{$&}/xg;
print encode('utf-8', $_);发布于 2017-01-16 05:10:34
local $/可以用于其他东西,而不是完全的静音。$/是输入记录分隔符,perl读取输入记录分隔符的所有内容,并包括输入记录分隔符,然后将其作为一行返回。$/的默认值是换行符( "\n" )。
如果将输入记录分隔符设置为undef,那么perl将永远不会在文件中找到输入记录分隔符,因此您将获得作为一行返回的整个文件。但您可以将输入记录分隔符设置为任何您想要的..。
$ cat data.txt
I don't want to proccess
this part of the file.
\begin{document}
I just want to process
the stuff down here.
\begin{document}
hellouse strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
my $fname = 'data.txt';
open my $INFILE, '<', $fname;
my ($unprocessed, $needs_processing);
{
local $/ = "\\begin{document}\n";
$unprocessed = <$INFILE>;
$/ = undef; #Read rest of file no matter what it contains.
$needs_processing = <$INFILE>;
}
close $INFILE;
print $unprocessed;
say '-' x 10;
print $needs_processing;
--output:--
I don't want to proccess
this part of the file.
\begin{document}
----------
I just want to process
the stuff down here.
\begin{document}
hello如果要对文件进行内部编辑:
use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
my $fname = 'data.txt';
my $divider = "\\begin{document}\n";
my $backup = '.bak';
open my $INFILE, '<', $fname;
{
local ($^I, $/, @ARGV) = ($backup, $divider, $fname);
CHUNK:
while(<>) {
if($. == 1) { # $. is the line number (starts at 1)
print; #STDOUT has been redirected to the file 'data.txt'.
$/ = undef; #Read rest of file no matter what it contains.
next CHUNK;
}
#Process $_ here:
s/e/E/g;
print; #STDOUT has been redirected to the file 'data.txt'.
}
}
close $INFILE;$ cat data.txt
I don't want to proccess
this part of the file.
\begin{document}
I just want to procEss
thE stuff down hErE.
\bEgin{documEnt}
hEllo原始文件将在data.txt.bak中。如果不需要备份,请将一个空字符串分配给$^I。
注意,在您的代码中,语句:
local $/;没有什么有用的东西。在您的代码中,该语句不在块内(=被大括号包围的部分代码)。local $/说:
$/的原始值保存在某个地方。$/。local $/的块退出时,将原始值赋值给$/。但是,由于local $/;不在代码中的一个块中,所以不会退出任何块,并且永远不会恢复$/的原始值。因此,没有必要保存$/的原始值。
https://stackoverflow.com/questions/41661532
复制相似问题