Programming Fundamentals/Loops/Perl

loops.pl

edit
#!/usr/bin/perl

# This program demonstrates While, Do, and For loop counting using 
# user-designated start, stop, and increment values.
#
# References:
#     https://en.wikibooks.org/wiki/Perl_Programming

sub get_value {
    my ($name) = @_;
    my $value;
    
    print 'Enter ' . $name . ' value:', "\n";
    $value = <>;
    chomp($value);
    
    return $value;
}

sub while_loop {
    my ($start, $stop, $increment) = @_;
    print 'While loop counting from ' . $start . ' to ' . $stop . 
        ' by ' . $increment . ':', "\n";
    my $count;
    
    $count = $start;
    while ($count <= $stop) {
        print $count, "\n";
        $count = $count + $increment;
    }
}

sub do_loop {
    my ($start, $stop, $increment) = @_;
    print 'Do loop counting from ' . $start . ' to ' . $stop . 
        ' by ' . $increment . ':', "\n";
    my $count;
    
    $count = $start;
    do {
        print $count, "\n";
        $count = $count + $increment;
    } while ($count <= $stop);
}

sub for_loop {
    my ($start, $stop, $increment) = @_;
    print 'For loop counting from ' . $start . ' to ' . $stop . 
        ' by ' . $increment . ':', "\n";
    my $count;
    
    for ($count = $start; $count <= $stop; $count += $increment) {
        print $count, "\n";
    }
}

sub main {
    my $start;
    my $stop;
    my $increment;
    
    $start = get_value('starting');
    $stop = get_value('ending');
    $increment = get_value('increment');
    
    while_loop($start, $stop, $increment);
    do_loop($start, $stop, $increment);
    for_loop($start, $stop, $increment);
}

main()

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Perl compiler / interpreter / IDE.

See Also

edit