[英]Perl save print as variable
I have a command 我有一个命令
print $_->{href} . "\n" for $mech->find_link_dom(text_regex => qr/pdf/i);
that prints out the exact link I would like to save as a variable. 打印出我想另存为变量的确切链接。 Although when I try to do
虽然当我尝试去做
my $link = $_->{href} . "\n" for $mech->find_link_dom(text_regex => qr/pdf/i);
it does not work. 这是行不通的。
Any thoughts? 有什么想法吗?
If you know that $mech->find_link_dom(text_regex => qr/pdf/i)
returns exactly one element, then you can write: 如果您知道
$mech->find_link_dom(text_regex => qr/pdf/i)
返回一个元素,则可以编写:
my $link = [$mech->find_link_dom(text_regex => qr/pdf/i)]->[0]->{href} . "\n";
If it can return multiple elements — or zero elements — then maybe you mean this: 如果它可以返回多个元素(或零个元素),那么您可能的意思是:
my $link;
$link .= $_->{href} . "\n" for $mech->find_link_dom(text_regex => qr/pdf/i);
Your first code snippet is equivalent to: 您的第一个代码段等效于:
for $_ ($mech->find_link_dom(text_regex => qr/pdf/i)) {
print $_->{href} . "\n"
}
The second is equivalent to: 第二个等效于:
for $_ ($mech->find_link_dom(text_regex => qr/pdf/i)) {
my $link = $_->{href} . "\n";
}
So, the $link
variable is local to the for
block, and is not visible outside of that block. 因此,
$link
变量for
块而言是本地的,在该块之外不可见。 It will work if you first declare the variable outside of the block: 如果您首先在块外声明变量,它将起作用:
my $link;
for $_ ($mech->find_link_dom(text_regex => qr/pdf/i)) {
$link = $_->{href} . "\n";
}
Or, using the short form as in your code: 或者,使用代码中的简写形式:
my $link;
$link = $_->{href} . "\n" for $mech->find_link_dom(text_regex => qr/pdf/i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.