sách gpt4 ăn đã đi

xml - 无法读取子内部的公共(public)标量

In lại 作者:数据小太阳 更新时间:2023-10-29 02:50:19 30 4
mua khóa gpt4 giày nike

perl 代码如下:问题是我无法读取 sub tweak_server{} 中的 $key ....

my $key;
my %hash = ( flintstones => [ "C:/Users1/f1.xml", "C:/Users1/f2.xml" ],
jetsons => [ "C:/Users2/f1.xml" ],
simpsons => [ "C:/Users3/f1.xml", "C:/Users3/f1.xml", "C:/Users3/f1.xml" ], );

foreach $key (keys%hash){
if (scalar@{$hash{$key}}>1){
foreach my $path (@{$hash{$key}}){
my $filehandle;
open($filehandle, "+<$path") or die "cannot open out file out_file:$!";
my $roots = { TAG => 1 };
my $handlers = { 'ROOT/TAG' => \&tweak_server,
};
my $twig = new XML::Twig(TwigRoots => $roots,
TwigHandlers => $handlers,
twig_print_outside_roots => \*$filehandle);
$twig->parsefile($path);
say $key;#could read key
sub tweak_server {
my ($twig, $root) = @_;
my $tag2=$root->first_child_text('TAG2');
say $key;# could not read
if ($tag2=~/$key/){
#BLABLA
}
$twig->flush( $filehandle, pretty_print => 'indented');
}
}
}

正如我所说,$key 可以在 sub 外部读取,但不能在内部读取。出现错误:使用未初始化的值 $key

然后我尝试了一个简单的情况,就像

my $a="aaa";
open( $filehandle, "+<$path") or die "cannot open out file out_file:$!";
my $roots = { TAG => 1 };
my $handlers = { 'ROOT/TAG' => \&tweak_server,
};
my $twig = new XML::Twig(TwigRoots => $roots,
TwigHandlers => $handlers,
twig_print_outside_roots => \*$filehandle
);
$twig->parsefile($path);
sub tweak_server {
say $a;
my ($twig, $root) = @_;
my $tags=$root->first_child_text('TAG2');
my $str="204B";
if ($tag2=~m/$str/){
foreach my $b(1...6){
say $a; }
}
$twig->flush( $filehandle, pretty_print => 'indented');

}

在这段代码中,可以读取 $a....我花了一天时间解决这个问题,但仍然无法修复它......现在疯了提前致谢!!

câu trả lời hay nhất

您在 循环之外声明了 $chìa khóa。然后,在 for 循环内,您定义了一个在 $chìa khóa 上关闭的子例程。

作为一般规则,在最小适用范围内声明变量。例如:

for my $key (keys ...) {

hoặc

open my $filehandle, '<', ...

为什么要在 循环体中定义 sub tweak_server?在我看来,您想要做的是为每次迭代定义一个新的匿名子。

首先,一个简短的例子可以复现您所观察到的内容:

use warnings; use strict;

my $key;
my %hash = qw(a b c d e f);

foreach $key (keys %hash) {
somesub();
sub somesub {
print "$key\n";
}
}

现在,修复:

use warnings; use strict;

my %hash = qw(a b c d e f);

foreach my $key (keys %hash) {
my $somesub = sub { print "$key\n" };
$somesub->();
}

这样,我们在每次迭代时定义一个新的匿名函数,并且每个新的子函数都会关闭循环变量的每个值。

就您的代码而言,您应该将命名的 sub 替换为

my $tweak_server = sub {
my ($twig, $root) = @_;
my $tag2=$root->first_child_text('TAG2');
say $key;# could not read
if ($tag2=~/$key/){
#BLABLA
}
$twig->flush( $filehandle, pretty_print => 'indented');
}

my $handlers = {
'ROOT/TAG' => $tweak_server,
};

或者,更好的是,正如@mirod 观察到的那样,将 $chìa khóa 传递给 tweak_server:

sub tweak_server { 
my( $key, $twig, $root)= @_;
...
}

并且,在循环体中,

my $handlers = { 
'ROOT/TAG' => sub { tweak_server($key, @_) },
};

关于xml - 无法读取子内部的公共(public)标量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7839384/

30 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress