1){ foreach my $a ($args[1..$argsize-1]) { -6ren">
gpt4 book ai didi

perl - "Use of unitialized value $. in range (or flip)"试图用 Perl 告诉我什么

转载 作者:行者123 更新时间:2023-12-03 23:00:15 27 4
gpt4 key购买 nike

我在 Perl 中有以下代码片段:

my $argsize = @args;
if ($argsize >1){
foreach my $a ($args[1..$argsize-1]) {
$a =~ s/(.*[-+*].*)/\($1\)/; # if there's a math operator, put in parens
}
}

执行时我得到“Use of unitialized value $. in range (or flip) , followed by Argument ""isn't numeric in array element at... 都指向 foreach 行。

有人可以帮我解读错误消息(并解决问题)吗?我有一个字符串数组@args。代码应该循环遍历第二个到第 n 个元素(如果存在的话),如果它们包含 +、- 或 *,则用 () 包围单个 args。

我不认为错误源于 args 中的值,我认为我以某种方式搞砸了范围......但是当 args 有 > 1 个元素时我失败了。一个例子可能是:

<"bla bla bla">  <x-1>  <foo> 

最佳答案

总而言之 - 您的 foreach 行 损坏了:

foreach my $a (@args[1..$argsize-1]) {

工作正常。这是因为您使用的是表示“标量值”的 $ 而不是表示数组(或列表)的 @

如果您使用诊断,您会得到;

Use of uninitialized value $. in range (or flip) at (W uninitialized) An undefined value was used as if it were already defined. It was interpreted as a "" or a 0, but maybe it was a mistake. To suppress this warning assign a defined value to your variables.

To help you figure out what was undefined, perl will try to tell you the name of the variable (if any) that was undefined. In some cases it cannot do this, so it also tells you what operation you used the undefined value in. Note, however, that perl optimizes your program and the operation displayed in the warning may not necessarily appear literally in your program. For example, "that $foo" is usually optimized into "that " . $foo, and the warning will refer to the concatenation (.) operator, even though there is no . in your program.

您可以通过以下方式重现此错误:

my $x = 1..3;

这实际上与您在这里所做的差不多——您正在尝试将一个数组值赋给一个标量。

这个问题有很多细节:

What is the Perl context with range operator?

但基本上:它将其视为范围运算符,就好像您正在处理文件一样。您将能够通过此运算符“作用于”文件中的特定行。

例如:

use Data::Dumper;
while (<DATA>) {
my $x = 2 .. 3;
print Dumper $x;
print if $x;
}

__DATA__
line one
another line
third line
fourth line

该范围运算符正在测试行号 - 因为您没有行号(因为您没有迭代文件)所以它出错了。 (但否则 - 它可能有效,但你会得到一些真的奇怪的结果;))

但我建议您以一种相当复杂的方式执行此操作,并(可能?)犯了一个错误,因为您的数组从 1 开始,而不是从零开始。

你可以改为:

s/(.*[-+*].*)/\($1\)/ for @args; 

结果相同。

(如果您需要跳过第一个参数:

my ( $first_arg, @rest ) = @args; 
s/(.*[-+*].*)/\($1\)/ for @rest;

但是运行时的错误是您输入的一些数据的结果。尽管如此,您在这里得到了什么:

use strict;
use warnings;

my @args = ( '<"bla bla bla">', '<x-1>', '<foo>' );

print "Before @args\n";
s/(.*[-+*].*)/\($1\)/ for @args;
print "After: @args\n";

关于perl - "Use of unitialized value $. in range (or flip)"试图用 Perl 告诉我什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31205292/

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