【发布时间】:2018-04-13 15:52:29
【问题描述】:
我正在尝试使用以下 Perl 代码提取图像 src 链接。不要得到我犯错误的地方。 1.打开一个文件并读取其中的URL
我的文本文件是这样的
https://zzzzzz.com/
https://yyyyyyy.com/
https://xxxxxxxxxx.com/
https://stackoverflow.com/
https://www.google.com/
https://www.yahoo.com/
-
foreach提取img src的文本文件中的URL - 将检索到的数据打印到另一个文件中
- 再次使用新文件句柄打开文件并将其读入数组
- 取消引用数组时显示错误
ARRAY(0x2e14a48) ARRAY(0x3125528) ARRAY(0x312e170)。
Perl 代码是
#!/usr/bin/perl
print "Content-type: text/html\n\n";
use strict;
use warnings;
use DBI;
use LWP::Simple;
use HTML::LinkExtor;
my $filename = "/path/to/file";
open FILE, '<', $filename or print "cant open file: $!";
my @data = <FILE>;
close(FILE);
my $image = "/path/to/file";
open FILES, '>', $image or print "cant write to file: $!";
foreach my $urls (@data) {
my $url = get("$urls");
my $linkextor = HTML::LinkExtor->new( \&links );
$linkextor->parse($url);
my $key;
sub links {
( my $tag, my %links ) = @_;
if ( $tag eq "img" ) {
foreach my $key ( keys %links ) {
if ( $key eq "src" ) {
foreach my $da ( @{$links{$key}} ) {
if ( $da =~ /^[a-zA-Z]/ ) {
print FILES "$da;\n";
} #if
} #foreach
} #if
} #foreach
} #if
} #sub
print FILES "\n";
} #foreach
close(FILES);
到此为止,没有问题我得到了所有的src链接,比如
https://zzzzzz.com/;https://yyyyyyy.com/;https://xxxxxxxxxx.com/;
https://zzzzzz.com/;https://yyyyyyy.com/;https://xxxxxxxxxx.com/;
https://zzzzzz.com/;https://yyyyyyy.com/;https://xxxxxxxxxx.com/;
https://zzzzzz.com/;https://yyyyyyy.com/;https://xxxxxxxxxx.com/;
这是我在文本文件中输出的格式,我只需要在图像列中按$image1, $image2, $image3 的顺序插入所有这些网址
my $platform = "mysql";
my $database = "xxx";
my $host = "xxxxx";
my $port = "xxxx";
my $user = "xxxxx";
my $pw = "xxxxxxxxx";
my $dbh = DBI->connect( "DBI:$platform:$database:$host:$port", $user, $pw );
open FILED, '<', $image or die "cannot open file: $!";
my @img = <FILED>;
close(FILED);
foreach my $lin (@img) {
chomp $lin;
my @in = split ';', $lin;
my $image1 = $in[0];
my $image2 = $in[1];
my $image3 = $in[2];
print "$image1 $image2 $image3 \n";
$sth->execute( $li, $val, $parsed, $htmls, $image1, $image2, $image3 );
}
exit;
我认为我在 foreach 循环中犯了错误,对吗?提前致谢。
【问题讨论】:
-
...为什么在 foreach 循环中嵌入了子定义?
标签: perl