[英]Why do I get “Syntax error near '$rocks['” in this Perl code?
When I run this program on ActivePerl 5.8 on Windows XP, I get a syntax error: 在Windows XP的ActivePerl 5.8上运行此程序时,出现语法错误:
#!C:\Perl\bin\perl.exe
use strict; # enabled
use warnings;
(my $rocks[0], my $rocks[1]) = qw/Hello World/; # Syntax error near '$rocks['
my $rocks[2] = 'Tom'; # Syntax error near '$rocks['
my $rocks[3] = 'Cat'; # Syntax error near '$rocks['
print $rocks[0];
print $rocks[1];
print $rocks[2];
print $rocks[3];
When I used ( @
) before the name of the array rocks
, it worked well. 当我在数组
rocks
的名称前使用( @
)时,它运行良好。 How do I fix the error above when I used $
? 使用
$
时,如何解决以上错误? Thank you. 谢谢。
my @rocks = qw{Hello World Tom Cat}; # worked well.
Don't use my
again and again to declare $rocks[0]
, $rocks[1]
etc. Declare the array once ( @rocks
) and use it. 不要一次又一次地使用
my
声明$rocks[0]
, $rocks[1]
等。一次声明数组( @rocks
)并使用它。
The corrected code is something like this: 更正后的代码是这样的:
use strict;
use warnings;
my @rocks; ## declare the array here
($rocks[0], $rocks[1]) = qw/Hello World/;
$rocks[2] = 'Tom';
$rocks[3] = 'Cat';
Use the push
operator: 使用
push
操作符:
my @rocks;
push @rocks, qw/ Hello World /;
push @rocks, "Tom";
push @rocks, "Cat";
Avoiding explicit and redundant array indices helps future-proof your code. 避免显式和冗余的数组索引可帮助您的代码适应未来需求。 For example, if you find you need to change your initialization, you can't botch an array index that isn't there.
例如,如果发现需要更改初始化,则无法破坏不存在的数组索引。
I think you need to declare my @rocks
and then not use my
any more when referring to $rocks[xxx]
. 我认为您需要声明
my @rocks
,然后在引用$rocks[xxx]
时不再使用my
。
If you don't know how many elements are going to be in there, you can use push
to add new elements into the (initially 0-sized) array. 如果您不知道其中有多少个元素,可以使用
push
将新元素添加到(最初为0大小)数组中。
You are redeclaring @rocks
several times. 您多次声明
@rocks
。 Try something like this instead: 尝试这样的事情:
my @rocks;
$rocks[0] = 'Tom';
$rocks[1] = 'Cat';
etc. 等等
You can first declare the array at the top as: 您可以首先在顶部将数组声明为:
my @rocks;
And remove my declaration from all other places. 并从其他所有地方删除我的声明。
Your code becomes: 您的代码变为:
#!C:\Perl\bin\perl.exe
# ActivePerl 5.8 based
use strict; # enabled
use warnings;
my @rocks;
($rocks[0], $rocks[1]) = qw/Hello World/; # Syntax error near '$rocks['
$rocks[2] = 'Tom'; # Syntax error near '$rocks['
$rocks[3] = 'Cat'; # Syntax error near '$rocks['
print $rocks[0];
print $rocks[1];
print $rocks[2];
print $rocks[3];
Why don't you just put it straight into @rocks
? 为什么不直接将它放入
@rocks
呢?
use strict;
use warnings;
my @rocks = qw'Hello World';
my $rocks[2] = 'Tom';
my $rocks[3] = 'Cat';
print $rocks[0];
print $rocks[1];
print $rocks[2];
print $rocks[3];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.