在 perl 的 @arr 中使用未初始化的值
Use of uninitialized value within @arr in perl
我有一个 Perl 脚本,它读取包含我的 SQL 文件的目录。
然后迭代这个数组并删除其中一个并打印出来。
@sqlArray = glob('C:/Users/Geeks/Folder/*.sql');
print Dumper(@sqlArray );
if( $company ne 'Geeks'){
my $index = 0;
my $count = scalar @sqlArray ;
$index++ until $sqlArray [$index] eq 'factura.sql' or $index==$count;
splice(@sqlArray , $index, 1);
}
print Dumper(@sqlArray );
我收到以下错误,我不知道它是怎么来的以及如何解决?
Use of uninitialized value within @sqlArray in string eq at /.../software/Queries.pl line 97.
欢迎提出任何想法并提前致谢。
my $count = scalar @sqlArray ;
$index++ until $sqlArray [$index] eq 'factura.sql' or $index==$count;
$count
是数组的大小。因此,数组中的最后一个索引是 $count-1
。您的代码正在尝试访问未定义的索引 $count
和 $count+1
。更好:
$index++ until $index==$count-1 or $sqlArray[$index] eq 'factura.sql';
或者更容易理解:
$index++ while $index<$count and $sqlArray[$index] ne 'factura.sql';
my $count = scalar @sqlArray ;
这为您提供了 @sqlArray
中的元素数。
or $index==$count
但随后您将其用作数组中的最后一个索引。它不是——它离数组末尾有一个位置(因为 Perl 数组索引从 0 开始)。如果你试图查看数组末尾以外的元素,Perl 会给你 undef
.
每个 Perl 数组都有一个关联的标量变量,它将为您提供数组中的最后一个索引。对于名为 @sqlArray
的数组,该变量称为 $#sqlArray
.
因此您可以完全删除 $count
变量并改用它:
$index++ until $sqlArray [$index] eq 'factura.sql' or $index==$#sqlArray;
问题是您访问了超出数组末尾的一个元素。该数组有 scalar(@sqlArray)
个元素,编号从 0
到 @sqlArray-1
(又名 $#sqlArray
),但您可以进一步访问一个。
当您想从数组中删除元素时,请考虑 grep
。
@sqlArray = grep { $_ ne 'factura.sql' } @sqlArray
if $company ne 'Geeks';
我有一个 Perl 脚本,它读取包含我的 SQL 文件的目录。
然后迭代这个数组并删除其中一个并打印出来。
@sqlArray = glob('C:/Users/Geeks/Folder/*.sql');
print Dumper(@sqlArray );
if( $company ne 'Geeks'){
my $index = 0;
my $count = scalar @sqlArray ;
$index++ until $sqlArray [$index] eq 'factura.sql' or $index==$count;
splice(@sqlArray , $index, 1);
}
print Dumper(@sqlArray );
我收到以下错误,我不知道它是怎么来的以及如何解决?
Use of uninitialized value within @sqlArray in string eq at /.../software/Queries.pl line 97.
欢迎提出任何想法并提前致谢。
my $count = scalar @sqlArray ;
$index++ until $sqlArray [$index] eq 'factura.sql' or $index==$count;
$count
是数组的大小。因此,数组中的最后一个索引是 $count-1
。您的代码正在尝试访问未定义的索引 $count
和 $count+1
。更好:
$index++ until $index==$count-1 or $sqlArray[$index] eq 'factura.sql';
或者更容易理解:
$index++ while $index<$count and $sqlArray[$index] ne 'factura.sql';
my $count = scalar @sqlArray ;
这为您提供了 @sqlArray
中的元素数。
or $index==$count
但随后您将其用作数组中的最后一个索引。它不是——它离数组末尾有一个位置(因为 Perl 数组索引从 0 开始)。如果你试图查看数组末尾以外的元素,Perl 会给你 undef
.
每个 Perl 数组都有一个关联的标量变量,它将为您提供数组中的最后一个索引。对于名为 @sqlArray
的数组,该变量称为 $#sqlArray
.
因此您可以完全删除 $count
变量并改用它:
$index++ until $sqlArray [$index] eq 'factura.sql' or $index==$#sqlArray;
问题是您访问了超出数组末尾的一个元素。该数组有 scalar(@sqlArray)
个元素,编号从 0
到 @sqlArray-1
(又名 $#sqlArray
),但您可以进一步访问一个。
当您想从数组中删除元素时,请考虑 grep
。
@sqlArray = grep { $_ ne 'factura.sql' } @sqlArray
if $company ne 'Geeks';