gpt4 book ai didi

在子例程中使用的 Perl 变量初始化错误

转载 作者:行者123 更新时间:2023-12-03 21:29:45 25 4
gpt4 key购买 nike

所以我有一个情况,我有一个带有两个命名参数的函数,但如果两个都被使用,则该函数需要终止。我不确定这是否是一个错误,或者是否存在我不了解 Perl 变量的内在原因。

这是简化的代码:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

foreach my $number (1..5)
{
fooBar(foo => $number);
}

sub fooBar
{
my %args = (
foo => undef,
bar => undef,
@_
);

my $foo = $args{foo} if defined $args{foo};
my @bar = @{$args{bar}} if defined $args{bar};
print Dumper(\@bar);

if (defined $foo)
{
die('fooBar() received both a foo and a bar and didn\'t know which to use!') if @bar;
push(@bar, $foo);
}

print Dumper(\@bar);
return (\@bar);
}

# > $VAR1 = [];
# > $VAR1 = [
# > 1
# > ];
# > $VAR1 = [
# > 1
# > ];
# > fooBar() received both a foo and a bar and didn't know which to use! at ./example.pl line 27.

这是我的解决方案:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

foreach my $number (1..5)
{
fooBar(foo => $number);
}

sub fooBar
{
my %args = (
foo => undef,
bar => undef,
@_
);

my $foo;
my @bar;
$foo = $args{foo} if defined $args{foo};
@bar = @{$args{bar}} if defined $args{bar};
print Dumper(\@bar);

if (defined $foo)
{
die('fooBar() received both a foo and a bar and didn\'t know which to use!') if @bar;
push(@bar, $foo);
}

print Dumper(\@bar);
return (\@bar);
}

# > $VAR1 = [];
# > $VAR1 = [
# > 1
# > ];
# > $VAR1 = [];
# > $VAR1 = [
# > 2
# > ];
# > $VAR1 = [];
# > $VAR1 = [
# > 3
# > ];
# > $VAR1 = [];
# > $VAR1 = [
# > 4
# > ];
# > $VAR1 = [];
# > $VAR1 = [
# > 5
# > ];

我的问题是,为什么这能解决问题?在第一个示例中,第一次调用 fooBar() 时,尽管 if 条件失败,但 @bar 正在初始化。第二次循环时,@bar 以某种方式保留了第一次循环中的信息,但它没有提示被重新初始化。在我看来,a) @bar 应该在子程序完成后被删除(这是我所期待的),b) @bar 不应该在之后初始化它未通过 if defined 测试,或者 c) @bar 应该提示它在循环中第二次被重新初始化。我在这里很困惑,这只是一个错误吗?

最佳答案

这只会有条件地创建一个新变量,并可能导致奇怪的结果:

my $foo = $args{foo} if defined $args{foo};

perldoc perlsyn有这样的话:

NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ... ) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

不要试图定义一个$foo变量;只需使用 $args{foo}。或者只是无条件地做作业;分配 undef 没有错。

关于在子例程中使用的 Perl 变量初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25331620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com