I used nested for loops(two of them) try to create this pattern, but I couldn't figure how to manipulate the height and width, so the reult will look like the answer.
here is my for loops, please give me some suggestions or hints so I can learn from it. Thanks!
for($i = 0; $i < $height; $i++)
#inner for loop will generate the columns
for($j = 0; $j < $width; $j++)
if($j == 0 || $ j == 10)--# first and last row missing full pattern
if($i == 0 || $i == 8)--- # first and last start in row 2-8 are missing
print " ";
#after previous row created, move cursor to the next row
I suppose that this is really evil, because although it works it will make you learn more about Perl than you really need for this problem if you want to explain it to your teacher, and it is decidedly NOT perl-think, but:
($w, $h) = (11, 9); $, = "\n";
print '*' x $w, ('*'.(' ' x ($w - 2)).'*') x ($h - 2), '*' x $w, '';
$, = "\n" sets the output field separator to newline. That means that when print is passed a list of arguments, it will separate each with a newline. Handy, but dangerous because $\ is a global variable. See perldoc perlvar for more info.
Let's take print's arguments apart:
'*' x $w : see perldoc perlop for a description of the 'x' operator. Here it takes a string and repeats it $w times. This returns a string.
(' ' x ($w - 2)) : Similar to the above, but note two things: $w - 2 is in parentheses due to precedence rules. So this is $w - 2 spaces.
'*'.(' ' x ($w - 2)).'*' : Use the concatenation operator to put stars before and after the spaces.
('*'.(' ' x ($w - 2)).'*') x ($h - 2) : Because of the parens, ('*'.(' ' x ($w - 2)).'*') is actually a single-item list. We then repeat that list $h - 2 times, making the inside of our figure.
, '' : That's just to force another newline for neatness.
Thus each line to be printed is an item in the list, so print's output field separator puts newlines after each one.