gpt4 book ai didi

regex - 在串联(.)或字符串中使用未初始化的值-Perl问题

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

我是第一次发布此信息。我在论坛中经历了类似的问题,但仍然无法确定为什么会收到此错误。

这是我要制作的示例代码。

use strict;
use warnings;
my ($m, $b) = @ARGV;
my $count_args = $#ARGV + 1;
my $times = 2**$m;
main();

sub main {
if ( $m =~ /^\d+$/ ) {
if ( $b =~ /^and$/i ) {
func_and();
} else {
print " not supported\n";
}
} else {
print " enter valid number of pins\n";
}
}
sub func_and {
my $bit;
for ( my $i = 0 ; $i < $times ; $i++ ) {
my $p = sprintf( "%0${m}b", $i );
print "$p\t";
my @c = split( '', $p );
my $result = 3;
foreach $bit (@c) {
if ( $result < 3 ) {
$result = $result && $bit;
} else {
$result = $bit;
}
}
print "result for AND operation on $bit is $result \n";
}
}

如果我将输入作为 perl AND.pl 2 and
我得到的错误是 Use of uninitialized value in concatenation (.) or string at NAND.pl line 34
还有其他方法来声明$位变量吗?以及如何初始化呢?
谢谢

最佳答案

更改:

print "result for AND operation on $bit is $result \n";

至:
print "result for AND operation on $p is $result \n";

然后,您可以将 $bit本地化为 foreach循环:
foreach my $bit (@c) {

perldoc perlsyn:

The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop.


$bit在循环之前未初始化,因此在循环之后仍保持不变。

关于regex - 在串联(.)或字符串中使用未初始化的值-Perl问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21940738/

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