Permalink
Browse files

let center use a character other than space

  • Loading branch information...
1 parent fddc162 commit fa977eec435c75b5296a6aa17a0cf0cdb8269334 @cowens committed Jun 23, 2009
Showing with 30 additions and 2 deletions.
  1. +17 −2 lib/perl5i.pm
  2. +13 −0 t/center.t
View
@@ -112,6 +112,14 @@ C<<$string>>.
say "Hello"->center(10); # " Hello ";
say "Hello"->center(4); # "Hello";
+ my $centered_string = $string->center($length, $character);
+
+Centers $string as above, but uses the character in $character
+instead of space.
+
+ say "Hello"->center(10, '-'); # "---Hello--"
+ say "Hello"->center(4, '-'); # "Hello";
+
=head2 die()
C<die> now always returns an exit code of 255 instead of trying to use
@@ -352,9 +360,16 @@ sub lstat {
sub SCALAR::center {
- my ($string, $size) = @_;
+ my ($string, $size, $char) = @_;
carp "Use of uninitialized value for size in center()" if !defined $size;
$size //= 0;
+ $char //= ' ';
+
+ if (length $char > 1) {
+ my $bad = $char;
+ $char = substr $char, 0, 1;
+ carp "'$bad' is longer than one character, using '$char' instead";
+ }
my $len = length $string;
@@ -368,7 +383,7 @@ sub SCALAR::center {
# bias the left padding to one more space, if $size - $len is odd
my $lpad = $padlen - $rpad;
- return ' ' x $lpad . $string . ' ' x $rpad;
+ return $char x $lpad . $string . $char x $rpad;
}
1;
View
@@ -27,6 +27,19 @@ warning_like {
'->center(undef)' );
} qr/^Use of uninitialized value for size in center\(\) at $0 line /;
+is( "even"->center(6, "-"), '-even-',
+ '->center(6, "-")' );
+
+is( "even"->center(7, "-"), '--even-',
+ '->center(7, "-")' );
+
+is( "even"->center(0, "-"), 'even',
+ '->center(0, "-")' );
+
+warning_like {
+ is( $hello->center(10, "-=-"), '---hello--',
+ '->center(undef)' );
+} qr/^'-=-' is longer than one character, using '-' instead at $0 line /;
# Test that center() always returns the correct length
for my $size ($hello->length..20) {

1 comment on commit fa977ee

@schwern

Ruby's implementation allows more than one character, don't see why not. "hello".center(20, '123') #=> "1231231hello12312312"

I'm a little concerned about the expansion of arguments, it might be worth while to go to named parameters. width => 10, pad => "-"

Please sign in to comment.