Reputation: 721
Currently I am doing this to read the individual contents of an array
my $size = @words;
for(my $x = 0; $x < $size, $x++)
{
print $words[$x];
}
Is there away to skip the $size assignment? A way to cast the array and have one less line?
i.e.
for(my $x = 0; $x < $(@word), $x++)
{
print $words[$x];
}
Can't seem to find the right syntax.
Thanks
Upvotes: 2
Views: 369
Reputation: 69264
The syntax that you are searching for is actually no syntax at all. If you use an array variable anywhere where Perl knows you should be using a scalar value (like as an operand to a comparison operator) then Perl gives you the number of elements in the array.
So, based on your example, this will work:
# Note: I've corrected a syntax error here.
# I replaced a comma with a semicolon
for (my $x = 0; $x < @words; $x++)
{
print $words[$x];
}
But there are several ways that we can improve this. Firstly, let's get rid of the ugly and potentially confusing C-style for
loop and replace it with a far easier to understand foreach
.
foreach my $x (0 .. @words - 1)
{
print $words[$x];
}
We can also improve on that @words - 1
. Instead, we can use $#words
which gives the final index in the array @words
.
foreach my $x (0 .. $#words)
{
print $words[$x];
}
Finally, we don't really need the index number here as we're just using it to access each element of the array in turn. Far better to iterate over the elements of the array rather than the indexes.
foreach my $element (@words)
{
print $element;
}
Upvotes: 1
Reputation: 385877
Replace
for (my $i = 0; $i < $(@words), $i++) { ... $words[$i] ... }
with
for (my $i = 0; $i < @words; $i++) { ... $words[$i] ... }
Just like in your assignment, an array evaluated in scalar context produces its size.
That said, using a C-style loop is complex and wasteful.
A better solution if you need the index:
for my $i (0..$#words) { ... $words[$i] ... }
A better solution if you don't need the index:
for my $word (@words) { ... $word ... }
Upvotes: 4
Reputation: 22274
Better to use foreach
, but to your specific question, @foo
in scalar context resolves to the length of the array, and $#foo
resolves to the index of the last element:
foreach my $word (@words) { ... } # preferred
for(my $i = 0; $i < @words; ++$i) { my $word = $words[$i]; ... } # ok sometimes
for(my $i = 0; $i <= $#words; ++$i) { my $word = $words[$i]; ... } # same thing
(assuming that you haven't played with $[
, which you shouldn't do.)
Upvotes: 3
Reputation: 164829
Yes, for
has a built in array iterator and for
and foreach
are synonyms.
for my $word (@words) {
print $word;
}
This is the preferred way to iterate through arrays in Perl. C style 3 statement for-loops are discouraged unless necessary. They're harder to read and lead to bugs, like this one.
for(my $x = 0; $x < $size, $x++)
^
should be a ;
Upvotes: 3