in reply to Re^2: Printing a hollow square of Asterisks
in thread Printing a hollow square of Asterisks

perl -le 'my $n = shift; die q{Please provide a positive number.} if ($n < 0); print q{*} x $n; if ($n > 1) { foreach (2 .. $n - 1) { print q{*}, q{ } x ($n - 2), q{*}; } print q{*{ x $n; }'

The above snippet takes a number afterward to select the size. In the case of nothing given, $n gets a value of 0. The q{*} x $n will give nothing if $n is 0, or $n asterisks. The if statement prevents the loop for the sides and printing a bottom if $n is 1. The loop is triggered only if $n - 1 is greater than 2 (ie, 3 or more), and prints only the asteristks on either edge, producing the "hole" in the middle.

Hope that helps.

Replies are listed 'Best First'.
Re^4: Printing a hollow square of Asterisks
by Rafter (Initiate) on Mar 04, 2009 at 15:42 UTC
    hey thanks for this.. but i cant seem to run this code..

      possible mis-use of single-quoting if you are on W32? Or, try:

      #!/usr/bin/perl -l use strict; use warnings; my $n = shift; # assign the number provided as an argue +ment to $n die q{Please provide a positive number.} if ($n < 0); # not negative print q{*} x $n; # print "*" $n times followed by newline +(the shebang's -l switch if ($n >1) { foreach (2 .. $n - 1) { # print second line .. next +to last line print q{*}, q{ } x ($n - 2), q{*}; # with $n-2 spaces (first & +last postions are * } print "*" x $n ; }

      Tested on *nix and W2k