tags:

views:

153

answers:

6

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.
+1  A: 

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.

Carl Smotricz
+1  A: 

You are redeclaring @rocks several times. Try something like this instead:

my @rocks;

$rocks[0] = 'Tom';
$rocks[1] = 'Cat';

etc.

klausbyskov
+11  A: 

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';
sateesh
Niggle: Please correct the references to `$rock[0]` and `$rock[1]` to refer to the correct variable.
darch
Thanks, I've made the correction
sateesh
+1  A: 

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];
RahulJ
+4  A: 

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.

Greg Bacon
This doesn't address the question.
darch
A: 

Why don't you just put it straight into @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];
Brad Gilbert