J2EEOnline J2EE





Perl Programming   «Prev 

Information Display of Perl

Every MouseOver and SlideShow has an accompanying Information Display for Perl.
This allows you to look at the content presented.
In this example MouseOver, you saw the following code fragment:

Perl while loop
Perl while loop
and were told that using while(<>) is shorthand for while(<STDIN>), which means while there is input from the keyboard.


Using While/Until Loops

The while statement has the general syntax of
while (expression)
block

The block is executed while the EXPRESSION is true.

my $i = 10;
while ( $i > 0 ) {
  if ( rand(3) > 2 ) {
    $i++;
  }
  else {
    $i--;
  }
  print $i,$/;
}

The previous code gradually lowers the value of $i until the expression $i > 0 evaluates as false. The main difference between while loops and for loops is that while loops iterate until a condition is false, whereas for loops iterate over a list. You commonly use the while loop in Perl with iterators, that is, the each() iterator for hashes.

What Is an Iterator?

The readline and glob functions, and the flip-flop operator, are all iterators when used in scalar context. A user-defined iterator usually takes the form of a code reference that calculates the next item in a list and returns it when executed.
When the iterator reaches the end of the list, it returns an agreed-upon value. While implementations vary, a subroutine that creates a closure around any necessary state variables and returns the code reference is common.
This technique is called a factory and facilitates code reuse.