CLOSE

A possible solution for the stars.pl program is as follows:

  1. #!/usr/bin/perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. # stars.pl - solution for printing out an increasing number of asterisks,
  7. # from 1 to 5. Uses a nested loop structure. For variety, a for()
  8. # loop is used on the outside and a while loop is used on the inside.
  9. # Many different types of loops could be used in either place.
  10.  
  11. my ($i, $j);
  12.  
  13. for ($i = 1; $i <= 5 ; $i++)
  14. {
  15. $j = 1;
  16. while ($j <= $i)
  17. {
  18. print '*';
  19. $j++;
  20. }
  21. print "\n";
  22. }
  23.  

Another possible solution is:

  1. #!/usr/bin/perl
  2.  
  3. use warnings;
  4. use strict;
  5.  
  6. # stars-foreach.pl - solution for printing out an increasing number
  7. # of asterisks, # from 1 to 5. Uses a nested loop structure using
  8. # foreach loops.
  9.  
  10. my ($i, $j);
  11.  
  12. foreach $i (1..5)
  13. {
  14. foreach $j (1..$i)
  15. {
  16. print '*';
  17. }
  18. print "\n";
  19. }
  20.  

A third possible solution is:

  1. #!/usr/bin/perl
  2.  
  3. # stars-xop.pl : alternate solution for stars.pl problem
  4. # uses the "x" operator which repeats a string (left operator)
  5. # a given number (right operator) of times. This avoids the
  6. # need for a loop with $j.
  7.  
  8. use warnings;
  9. use strict;
  10.  
  11. my $i;
  12.  
  13. for ($i = 1; $i <= 5 ; $i++)
  14. {
  15. print '*' x $i, "\n";
  16. }
  17.  

CLOSE