0

Hi i am studying some code based on arrays and I came accross the following:

@array; #contains lines of text

for (0 .. $#array - 2)
{
   #code here
}

What is the purpose of the 0 .. syntax? and what will it do based on the example? Also how is this different from writing foreach(@array -2)?

1
  • 2
    Did you mean foreach(0 .. @array-2)? If @array has 6 elements, $#array-2 (highest index minus 2) is 3 and @array-2 (number of elements minus 2) is 4. Commented Jan 18, 2015 at 22:50

1 Answer 1

5

.. is the range operator. It can be used in two rather different ways, depending on the context in which it occurs. In this case, you are using the list context, in which case your code

for (0 .. $#array - 2)

is similar to

for (local $_ = 0; $_ <= $#array - 2; $_++)

In other words, it creates a range of numbers, from 0 to $#array - 2.

The range operator can also be used in scalar context, in which case it keeps track of a state. But that is another question.

This is different from

foreach(@array -2)

Note that in this expression, the array @array is put in scalar context by the - operator, and will return its size. It will only create one value for the for loop, and that is the size of the array minus 2. Say the list has 10 elements, then you get:

foreach (8)

Which is just a loop over a list of one item (the number 8), and not very useful. So the difference is quite big, and not meaningful to explain, really. I assume you meant:

foreach (@array[0 .. $#array - 2])

Which is a loop using an array slice. In this case, you are looping over the values of the array, rather than over the indexes. E.g.

for (0 .. $#array) {
    print $array[$_];
}

vs

for (@array) {
    print $_;
}

You might also note that for and foreach mean exactly the same thing in Perl. They are aliases of each other, and there is no difference in how they work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.