Perl 中正则表达式编译中的未初始化值



当我使用 if-else 块比较$valid时,下面的代码给出了错误。如果未使用 if-else 条件,则不存在错误。错误是"在正则表达式编译中使用未初始化的值$value"。如何解决这个问题?

...
if($valid eq 1){
print "Enter valuen" ;
my $value = <STDIN>;
}else{
print " valid is not 1 n";
}
if($line =~ /$string.*$value/){  --> error
//code
}
  1. Perl 程序需要(pragma: A pragma is a module which influences some aspect of the compile time or run time behaviour of Perl, such as strict or warnings)。除非直到我们看到完整的代码。

  2. 请理解区块内外变量的声明。

进入您的代码:

if($valid eq 1)
{
print "Enter valuen" ;
my $value = <STDIN>;
#This the "$value" prints what you have get from the MS-Dos Prompt from the user.
#$value ends here since the $value has been declared this block
}

$value需要在if-else块之外声明您不会收到错误消息。

my $value = "";
if($valid eq 1)
{
print "Enter valuen" ;
$value = <STDIN>;
chomp($value); #Additionally, you should chomp (remove the entermark at end of the value $value;
}

谢谢。

我冒昧地更改了您的代码以使其正常工作 [在提示测试时输入]

use strict;
use warnings;
my $valid = '1';
my $value;
my $line    = 'Some lazy dog is taking a sun bath';
my $string  = 'lazy';
if($valid eq '1'){
print "Enter value: " ;
$value = <STDIN>;
chomp $value;
}else{
print " valid is not 1 n";
}
if( $line =~ /$string.*$value/ ){  
print 'Horay!!! I found the string - ';
print "$linen";
} else {
print "Sorry, no line foundn";
}

您的错误隐藏在$value的范围声明中 - 它仅对内部代码块有效- 我已将其移出if ...还。。。块。

注意:也许你打算写

my $valid = 1;
....
if( $valid ) {
....
} else {
....
}

虽然以下代码是有效的,但在这种特殊情况下是多余的(如果$valid不为零,则认为为真(

if( $valid == 1 ) {
....
} else {
....
}

数字和字符串的比较运算符

最新更新