简体   繁体   中英

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:

#!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. 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.

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:

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] .

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.

You are redeclaring @rocks several times. 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 ?

use strict;
use warnings;



my $rocks[2] = 'Tom';
my $rocks[3] = 'Cat';

print $rocks[0];
print $rocks[1];
print $rocks[2];
print $rocks[3];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM