fork download
  1. #!/usr/bin/perl
  2.  
  3. # 216 Pad a string on both sides
  4.  
  5. sub center {
  6. my ($s, $m, $c) = @_;
  7. my $slen = length $s;
  8. return $s if $slen > $m;
  9. $c //= ' ';
  10. my $r = $c x $m;
  11. my $p = int($m/2 - $slen/2);
  12. substr($r, $p, $slen, $s);
  13. return $r;
  14. }
  15.  
  16. printf "width %3d: %s\n", 10, center("abcd",10,"X");
  17. # the result should be "XXXabcdXXX".
  18.  
  19. foreach my $m ( 0..12 ) {
  20. printf "width %3d: %s\n", $m, center('xyz', $m, '-');
  21. }
  22.  
  23. printf "width %3d: %s\n", 12, center('xyz', 12) . '<-- c defaults to space';
  24.  
Success #stdin #stdout 0.01s 5424KB
stdin
Standard input is empty
stdout
width  10: XXXabcdXXX
width   0: xyz
width   1: xyz
width   2: xyz
width   3: xyz
width   4: xyz-
width   5: -xyz-
width   6: -xyz--
width   7: --xyz--
width   8: --xyz---
width   9: ---xyz---
width  10: ---xyz----
width  11: ----xyz----
width  12: ----xyz-----
width  12:     xyz     <-- c defaults to space