[英]Perl array in scalar context
I am a newbie in Perl. 我是Perl的新手。 I'm trying to understand Perl context.
我正在尝试了解Perl上下文。 I've the following Perl code.
我有以下Perl代码。
use strict;
use warnings;
use diagnostics;
my @even = [ 0, 2, 4, 6, 8 ];
my @odd = [ 1, 3, 5, 7, 9 ];
my $even1 = @even;
print "$even1\n";
When I execute the code, I get the following output ... 当我执行代码时,我得到以下输出...
1
But, as I've read, the following scalar context should places the number of elements in the array in the scalar variable. 但是,正如我所读到的,下面的标量上下文应该将数组中的元素数量放在标量变量中。
my $even1 = @even;
So, this is bizarre to me. 所以,这对我来说很奇怪。 And, what's going inside the code?
而且,代码内部会发生什么?
The correct syntax for defining your arrays is 定义数组的正确语法是
my @even = ( 0, 2, 4, 6, 8 );
my @odd = ( 1, 3, 5, 7, 9 );
When you use square brackets, you're actually creating a reference (pointer) to an anonymous array, and storing the reference in @even
and @odd
. 当您使用方括号时,您实际上是在创建一个匿名数组的引用 (指针),并将引用存储在
@even
和@odd
。 References are scalars, so the length of @even
and @odd
is one. 引用是标量,所以
@even
和@odd
的长度是1。
See the Perl references tutorial for more on references. 有关引用的更多信息,请参阅Perl参考教程 。
By using square brackets in Perl, you are creating an array reference rather than an actual array. 通过在Perl中使用方括号,您将创建一个数组引用而不是实际的数组。 You can read up on how references work in the manual:
perldoc perlreftut
. 您可以阅读手册中的参考资料:
perldoc perlreftut
。 Replace the square brackets with round parentheses and the code will do what you expect: 用圆括号替换方括号,代码将按预期执行:
my @even = ( 0, 2, 4, 6, 8 );
my @odd = ( 1, 3, 5, 7, 9 );
my $scalar = @even;
print "$scalar\n";
will print 将打印
5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.