tailieunhanh - Beginning Perl Third Edition PHẦN 4
Tại sao? Có bốn yếu tố trong mảng đó là giá trị vô hướng. Chỉ số của họ là 0, 1, 2, và 3. Vì chúng ta đang bắt đầu từ 0, chỉ số cao nhất ($ # mảng) sẽ luôn luôn là một trong ít hơn số phần tử trong mảng. Vì vậy, chúng ta đếm từ 0 đến chỉ số cuối cùng của câu hỏi @, | CHAPTER 4 LISTS AND ARRAYS Why There are four elements in the array so that s the scalar value. Their indices are 0 1 2 and 3. Since we re starting at 0 the highest index array will always be one less than the number of elements in the array. So we count up from 0 to the last index of questions which happens to be 3. We set the iterator to each number in turn. Where s the iterator Since we didn t give one Perl will use _. Now we do the block four times once when _ is 0 once when it is 1 and so on. print How many questions _ This line prints the zeroth element of questions the first time around then the first then the second third and fourth. print punchlines _ n n And so it is with the punchlines. If we d just said foreach questions _ would have been set to each question in turn but we would not have advanced our way through the answers. A quick note recall that the keywords for and foreach are synonyms for each other. We will stick to the style of calling a foreach a foreach but some Perl programmers call the foreach a for. This also applies to the expression modifier form of the foreach. Expression Modifier for the foreach Loop Just as there was an expression modifier form of if like this die Something wicked happened if error there s also an expression modifier form of foreach. This means you can iterate an array executing a single expression every time. Here however you don t get to choose your own iterator variable it s always _. It has this form statement foreach list_or_array Here is a quick example usr bin perl use warnings use strict my @a qw John Paul George Ringo print _ n foreach @a Running this code produces the following perl John Paul George 108 CHAPTER 4 LISTS AND ARRAYS Ringo Array Functions It s time we met some more of the operations we can perform with arrays. These are called array functions. We ve already met one of them reverse which we used to count down ranges instead of counting up. We can use reverse on arrays as .
đang nạp các trang xem trước