challenge 文字列のセンタリング

文字列を指定のカラム幅にセンタリング配置する関数を示してください。文字列の長さが指定した幅より長い場合には文字列の両端をできるだけ均等に切り落して指定幅に収めてください。1文字は1カラムに収まるものと仮定してかまいません。

Posted feedbacks - Perl

一番乗りかな?きわめてけれんみのない実装。

Dan the Perl Monger

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#!/usr/local/bin/perl
use strict;
use warnings;

sub center{
    my $str = shift;
    my $width = shift || 80;
    my $margin = int(($width - length($str))/2);
    return $str if $margin == 0;
    return " " x int($margin) . $str if $margin > 0;
    substr($str, 0, -$margin, '');
    return substr($str, 0, $width);
}

chomp and print center($_, 72), "\n" for(<>)
__END__
0         1         2         3         4         5         6         7
012345678901234567890123456789012345678901234567890123456789012345678901
This line is intentionally longer than 72 chars to test center() works fine.

Index

Feed

Other

Link

Pathtraq

loading...