In pursuit of this issue .

How to simplify and optimize code for outputting a diamond to perl?

It works, but after javascript it seems somewhat ugly, especially the construction in $ out and the second condition while:

$i = 1; print "Введите размер стороны: "; chomp($side = <STDIN>); $prob = $side - $i; $stend = ' ' x $prob . '#' . "\n"; print $stend; $i++; while ($i <= $side) { $prob = $side - $i; $out = ' ' x $prob . '#' . ' ' x (($i *2) - 3) . '#'; print $out . "\n"; $i++; } $i--; while ($i > 2) { $i--; $prob = $side - $i; $out = ' ' x $prob . '#' . ' ' x (($i *2) - 3) . '#'; print $out . "\n"; } print $stend . "\n"; 

In the online interpreter: Link to code

UPD: in $ out confuses the calculation *2) - 3 )

    1 answer 1

    You yourself asked to reduce ... well ...

     print "Введите размер стороны: "; chomp($side = <STDIN>); print ' ' x ($side-$_) . '#' . ' ' x (($_ *2) - 3) . ($_==1?'':'#')."\n" for (1..$side, reverse 1..$side-1); 

    And the construction "in $ out" had to complicate a little ...

    You can try to simplify the design of the print, creating a line to the middle and symmetrically expand it, I do not know if this is a simplification or a complication:

     print "Введите размер стороны: "; chomp($side = <STDIN>); for (1..$side,reverse 1..$side-1) { $a=' ' x ($side-$_) . "#" . ' ' x ($_-2); print $a, ' ', ($_==1 ? '': scalar reverse $a), "\n"; } 

    And finally, the option of replacing the space in the right places with a sharp:

     print "Введите размер стороны: "; chomp($side = <STDIN>); for (1..$side, reverse 1..$side-1) { $a=" "x($side*2); substr($a,$_-1,1)='#' for $side-$_+1, $side+$_-1; print "$a\n"; } 

    Yes, in perl, the replacement takes place in this “strange” way, first substr() “select” the position in the line in which you need to change something, and then assign this “position” a new value.

    • Uh ... Why explain? I know why - I wrote this =) I didn’t like the construction in $ out either. Eyes cuts. And for the idea of ​​stuffing for directly into print - thanks - Alexandr Blinov
    • @AlexandrBlinov And another option ... - Mike
    • @AlexandrBlinov, "stuff for directly into print" - nobody stuffed anything anywhere. This is the usual postfix for for . BTW, Perlcritic doesn't love her :) - PinkTux