我.html在一個目錄中有一些檔案,我想向其中添加一行css代碼。使用perl,我可以使用正則運算式定位位置并添加css代碼,這非常有效。
但是,我的第一個 .html 檔案包含一個帶重音的字母:é,但生成的.html檔案存在編碼問題并列印:\xE9
在 perl 檔案中,我UTF-8在打開和關閉檔案時一直小心地指定編碼,如下面的 MWE 所示,但這并不能解決問題。我該如何解決這個編碼錯誤?
移動電源
use strict;
use warnings;
use File::Spec::Functions qw/ splitdir rel2abs /; # To get the current directory name
# Define variables
my ($inputfile, $outputfile, $dir);
# Initialize variables
$dir = '.';
# Open current directory
opendir(DIR, $dir);
# Scan all files in directory
while (my $inputfile = readdir(DIR)) {
#Name output file based on input file
$outputfile = $inputfile;
$outputfile =~ s/_not_centered//;
# Open output file
open(my $ofh, '>:encoding(UTF-8)', $outputfile);
# Open only files containning ending in _not_centered.html
next unless (-f "$dir/$inputfile");
next unless ($inputfile =~ m/\_not_centered.html$/);
# Open input file
open(my $ifh, '<:encoding(UTF-8)', $inputfile);
# Read input file
while(<$ifh>) {
# Catch and store the number of the chapter
if(/(<h2)(.*?)/) {
# $_ =~ s/<h2/<h2 style="text-align: center;"/;
print $ofh "$1 style=\"text-align: center;\"$2";
}else{
print $ofh "$_";
}
}
# Close input and output files
close $ifh;
close $ofh;
}
# Close output file and directory
closedir(DIR);
名為“Chapter_001_not_central.html”的有問題的檔案
<html >
<head></head>
<body>
<h2 ><span >Chapter 1</span><br /><a id="x1-10001"></a>Brocéliande</h2>
Brocéliande
</body></html>
uj5u.com熱心網友回復:
以下演示腳本確實需要使用glob函式進行注入。
注意:腳本創建一個新檔案,取消重命名注釋以使用新檔案替換原始檔案
use strict;
use warnings;
use open ":encoding(Latin1)";
my $dir = '.';
process($_) for glob("$dir/*_not_centered.html");
sub process {
my $fname_in = shift;
my $fname_new = $fname_in . '.new';
open my $in, '<', $fname_in
or die "Couldn't open $fname_in";
open my $out, '>', $fname_new
or die "Couldn't open $fname_new";
while( <$in> ) {
s/<h2/<h2 style="text-align: center;"/;
print $out $_;
}
close $in;
close $out;
# rename $fname_new, $fname_in
# or die "Couldn't rename $fname_new to $fname_in";
}
如果您不介意按單個檔案運行以下腳本 script.pl in_file > out_file
use strict;
use warnings;
print s/<h2/<h2 style="text-align: center;"/ ? $_ : $_ for <>;
如果這種任務只是偶爾出現,那么它可以用一個班輪解決
perl -pe "s/<h2/<h2 style='text-align: center;'/" in_file
uj5u.com熱心網友回復:
這個問題在@Shawn 和@sticky bit 的評論中找到了答案:
通過將打開和關閉檔案的編碼更改為 ISO 8859-1,它解決了問題。如果你們中的一個想發布答案,我會驗證它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349241.html
上一篇:了解Perl包命名空間
