Perl 如何使此搜索和替换代码更好?
我有这个密码Perl 如何使此搜索和替换代码更好?,perl,Perl,我有这个密码 #!/usr/bin/perl use warnings; use strict; my %map; open my $MAP, '<', 'full_links' or die $!; while (<$MAP>) { my ($key, $value) = /comments\/(.*)\/(.*)\//; $map{$key} = "$key/$value"; } open my $IN, '<', 'html_links' or
#!/usr/bin/perl
use warnings;
use strict;
my %map;
open my $MAP, '<', 'full_links' or die $!;
while (<$MAP>) {
my ($key, $value) = /comments\/(.*)\/(.*)\//;
$map{$key} = "$key/$value";
}
open my $IN, '<', 'html_links' or die $!;
open my $out, '>', "results" or die;
while (<$IN>) {
s/comments\/(.*)"/comments\/$map{$1}\/"/g;
print $out $_;
}
close $out;
#/usr/bin/perl
使用警告;
严格使用;
我的%map;
打开我的$MAP,“我会用它。让它找到所有A标记,然后更改它们的HREF值:
#!perl
use v5.14;
use Mojo::DOM;
use Mojo::URL;
my $html = <<'HERE';
<html>
<body>
<a href="https://reddit.com/r/subreddit/comments/CODE/">Some title</a>
<a href="https://example.com/">Leave alone</a>
<a href="https://reddit.com/r/subreddit/comments/CODE/">Other title</a>
</body>
</html>
HERE
# Create the Document object model
my $dom = Mojo::DOM->new($html);
$dom
# find all the A tags in the HTML with CSS selectors
# The ^= matches just the HREFs that start with that text
->find( 'a[href^=https://reddit.com/]' )
->map( sub {
# take the slug from the text between the A opener and closer.
# replace whitespace (or whatever) with underscores
my $slug = lc($_->text) =~ s/\s+/_/gr;
# add the slug to the last part of the URL's path
my $url = Mojo::URL->new( $_->attr('href') );
push $url->path->parts->@*, $slug;
# give the HREF its new value
$_->attr('href', $url)
})
;
# The DOM now has the modified HTML
say $dom
#!perl
使用v5.14;
使用Mojo::DOM;
使用Mojo::URL;
my$html=find('a[href]^=https://reddit.com/]' )
->地图(附属){
#从开瓶器和闭口器之间的文本中取出段塞。
#用下划线替换空白(或任何内容)
我的$slug=lc($\ux->text)=~s/\s+/\ugr;
#将slug添加到URL路径的最后一部分
我的$url=Mojo::url->new($u979;->attr('href');
按$url->path->parts->@*,$slug;
#为HREF指定其新值
$\属性('href',$url)
})
;
#DOM现在已经修改了HTML
比如说$dom
像处理普通文本一样处理HTML容易比您最初期望的更困难。您可能需要花一个小时左右的时间学习使用Mojo::DOM,它内置了DOM搜索和替换功能,这样做将解锁一项可能有用的新技能。是的,正如DavidO所说的那样学习HTML库(Mojo::DOM
,HTML::TreeBuilder
),这是您可以从这个(简单的)任务中获得的一件好事。但是,还有…(1)code
不应该是…
价值的关键和title\u吗?所以$map{$key}=$value代码>。但由于这些名称没有提供信息,可能$title{$code}=$text使用中的[^/]
(3)而不是贪婪(和回溯)*(2)在中使用[^/]
(3),而只替换code
之后的下一个/…/
段——查找\K
,以删除到该点的所有匹配项(因此您不必重新键入它们)。///将代码提交给“代码审查”,如果代码没有损坏,就不要修复它。您试图解决的问题/增强功能是什么?