使用perl替换文件

时间:2015-10-29 05:11:34

标签: perl

使用以下代码,我想将html标记“<div class="blank">\n<p>”替换为“<table>\n<tr>”。但我们无法将<div class="blank">替换为<table>,将<p>替换为<tr>,因为不同格式的内容会更多。

use warnings ;
use strict;
my $directory = <STDIN>;
chomp($directory); #Remove the last enter from the key board
    foreach my $fp (glob("$directory/*.html"))
        {
            open (read_file, '<:encoding(UTF-8)', $fp)  or die "Could not open file '$fp' $!";
            my @fh = <read_file>;
            close(read_file);
            my @o_filename = split '\/' , $fp;
            my $f_name_split = $o_filename[-1];
            my @f_nmae = split '\.' , $f_name_split;
            unlink ($fp);
            my @newlines;
            foreach(@fh)
                {   
                    $_ =~ s/<div class="blank">\n<p>/<table>\n<p>/;
                    push(@newlines, $_);
                }
                open(write_file, ">$directory\/$f_nmae[0].htm") || die "File not found";
                print write_file @newlines;
                close(write_file);
        }
        print ("\n\t----------------Done----------------\n");

输入: -

<div class="blank">
<p>songs</p>

输出: -

<table>
<tr>songs</p>

1 个答案:

答案 0 :(得分:0)

改变这个:

$_ =~ s/<div class="blank">\n<p>/<table>\n<p>/;

为:

s/<div class="blank">/<table>/;
s/<p>songs<\/p>/<tr>songs<\/p>/;

其他人不需要新阵列。这段代码:

my @newlines;
foreach(@fh)
{   
    $_ =~ s/<div class="blank">\n<p>/<table>\n<p>/;
    push(@newlines, $_);
}
open(write_file, ">$directory\/$f_nmae[0].htm") || die "File not found";
print write_file @newlines;
close(write_file);

可以写成:

foreach(@fh)
{   
    s/<div class="blank">/<table>/;
    s/<p>songs<\/p>/<tr>songs<\/p>/;
}
open $write_file, ">$directory\/$f_nmae[0].htm" or die "File not found: $!";
print $write_file @fh;
close $write_file;

您可以修改@fh本身。并始终使用词法文件句柄。