Brand Newbie to perl.
Playing around trying to get a feel for how arrays work and encountered error in title.

#!/usr/bin/perl -w
use strict;

my(@array) = (10, 20, 30, 40, 50, 60);
my($marker);
my($EOA) = @array;

for ($marker = 0; $marker <= $EOA ; $marker++){
print "@array[$marker]\n"; #line where error encountered
}


To me with a 'C' background this looks valid.
Creating a marker to move through the array element by element.
Do not understand why I get the error when running code.

Please help to identify cause so I gain understanding of how perl works.

Thank You,

Perlfan!

Recommended Answers

All 2 Replies

Okay, so I've banished the error with the following syntax:

#!/usr/bin/perl -w
use strict;

my(@array) = qw(10, 20, 30, 40, 50, 60);
my($idx);

for ($idx = 0; $idx <= $#array ; $idx++){
print "$array[$idx]\n";
}


That said, I would still like to know why the previous syntax gave me an error.
May seem redundant but I do software testing and always want to know the whys behind the issues.

(Those who do not know the past (coding errors) are doomed to repeat them)

You never said what error you were getting but I am assuming you were getting a warning and not an array.

Scalar value @array[$marker] better written as $array[$marker] at script line 9 .

When accessing individual elements of an array you use the scalar data type symbol $ and not the list/array data type symbol @.

But perl has 'for' and 'foreach' loops to loop through an entire array or you should use the perlish style of indexed looping:

#!/usr/bin/perl -w
use strict;

my @array = (10, 20, 30, 40, 50, 60);

for my $i (0..$#array){
   print "$array[$i]\n";
}

indexed looping is really only necessary when you don't need to loop through an entire array or might want to skip over the odd or even elements of an array, otherwise use for/foreach (which are the same).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.