Programming Basics

  Home arrow Programming Basics arrow Control Flow Constructs: Loops Conclus...
PROGRAMMING BASICS

Control Flow Constructs: Loops Conclusion
By: Apress Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating:  stars stars stars stars stars / 0
    2012-04-04

    Table of Contents:
  • Control Flow Constructs: Loops Conclusion
  • Reexecuting the Loop
  • Loop Labels

  •  
     

    SEARCH CODEWALKERS

    Control Flow Constructs: Loops Conclusion


    (Page 1 of 3 )

    In this conclusion to a nine-part article series on Perl control flow constructs, you'll learn about the the next function and how to re-execute a loop. This article is excerpted from chapter three of the book Beginning Perl, Second Edition, written by James Lee (Apress; ISBN: 159059391X).

    Going On to the Next

    If you want to skip the rest of the processing of the body, but donít want to exit the loop, you can use next to immediately go execute the next iteration of the loop by testing the expression. Here is an example of a program that reads input from the user, and if the line of input is not blank, the line is printed. It the line is blank, then we immediately go back to read the next line:

    #!/usr/bin/perl -w
    # next1.pl

    use strict;

    print "Please enter some text:\n";
    while (<STDIN>) {
    if ($_ eq "\n") {
    next;
    }
    chomp;
    print "You entered: [$_]\n";
    }

    Here is an example of running this program in Windows:

    $ perl next1.pl
    Please enter some text:
    testing
    You entered: [testing]
    one
    You entered: [one]
    two three
    You entered: [two three]
    ^Z<enter>
    $

    Notice that when the user entered a blank line, then the program immediately read the next line of input.

    This program could have be written with an expression modifier:

    #!/usr/bin/perl -w
    # next2.pl

    use strict;

    print "Please enter some text:\n";
    while (<STDIN>) {
    next if $_ eq "\n";
    chomp;
    print "You entered: [$_]\n";
    }

    More Programming Basics Articles
    More By Apress Publishing

    blog comments powered by Disqus

    PROGRAMMING BASICS ARTICLES

    - The Transliteration Operator in Perl
    - Perl String Processing Functions
    - Perl String Processing
    - Control Flow Constructs: Loops Conclusion
    - Loop Control Constructs
    - Control Flow Constructs: the For and Foreach...
    - Loops and Control Flow Constructs
    - Expression Modifiers for Perl Control Flow C...
    - Logical Operators and Control Flow Constructs
    - Comparing Strings with Control Flow Construc...
    - Perl Operators and Control Flow Constructs
    - Control Flow Constructs
    - More Time Manipulation with PHP
    - Validating and Manipulating Dates with PHP
    - Using the Date Constructor in PHP

    Developer Shed Affiliates

     



    © 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap