gpt4 book ai didi

arrays - 如何在 Perl 中引用拆分表达式?

转载 作者:行者123 更新时间:2023-12-03 14:30:22 25 4
gpt4 key购买 nike

我想创建对通过 Perl 拆分获得的数组的引用。
我在想类似的事情:

my $test = \split( /,/, 'a,b,c,d,e');

foreach $k (@$test) {
print "k is $k\n";
}

但这提示 Not an ARRAY reference at c:\temp\test.pl line 3.我尝试了其他一些替代方案,均未成功。

最佳答案

背景说明:

split和其他函数一样,返回一个列表。您不能引用列表。但是,如果将引用运算符应用于列表,它将应用于其所有成员。例如:

use Data::Dumper;

my @x = \('a' .. 'c');

print Dumper \@x

输出:
$VAR1 = [          \'a',          \'b',          \'c'        ];

Therefore, when you write my $test = \split( /,/, 'a,b,c,d,e');, you get a reference to the last element of the returned list (see, for example, What’s the difference between a list and an array?). Your situation is similar to:

Although it looks like you have a list on the righthand side, Perl actually sees a bunch of scalars separated by a comma:

my $scalar = ( 'dog', 'cat', 'bird' );  # $scalar gets bird

Since you’re assigning to a scalar, the righthand side is in scalar context. The comma operator (yes, it’s an operator!) in scalar context evaluates its lefthand side, throws away the result, and evaluates it’s righthand side and returns the result. In effect, that list-lookalike assigns to $scalar it’s rightmost value. Many people mess this up becuase they choose a list-lookalike whose last element is also the count they expect:

my $scalar = ( 1, 2, 3 );  # $scalar gets 3, accidentally


在您的情况下,您在 RHS 上获得的是对 split 返回的列表元素的引用列表。 ,并且该列表的最后一个元素以 $test 结束。 .您首先需要从这些返回值构造一个数组并对其进行引用。您可以通过形成一个匿名数组并将对该数组的引用存储在 $test 中来创建一条语句。 :
my $test = [ split( /,/, 'a,b,c,d,e') ];

关于arrays - 如何在 Perl 中引用拆分表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8444661/

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