开发者

Perl print formatting

I would like to format(truncate/append with chars) a string to a specified length while printing in Perl.

For example

$string='my_string';
printf("%04s",$string);

should print

my_s

also if

$string='my';

I should get

00my

Is there any way to print last four characters ?

ring

and if string is

$string='my开发者_如何学C';

it should print

00my


You want to do this format string instead of yours:

printf ("%04.4s", $string);

You need the .4 because this specifies maximum length. (The 4 at the beginning specifies a minimum only)

here are the output of some tests:

$ perl -e "my \$string = \"my_string\";print sprintf(\"%04.4s\", 22);"
0022
$ perl -e "my \$string = \"my_string\";print sprintf(\"%04.4s\", \$string);"
my_s
$ perl -e "my \$string = \"my\";print sprintf(\"%04s\", \$string);"
00my

Here is the output using the wrong format string. As you can see strings are not truncated.

$ perl -e "my \$string = \"my_string\";print sprintf(\"%04s\", 22);"
0022
$ perl -e "my \$string = \"my_string\";print sprintf(\"%04s\", \$string);"
my_string


printf('%04s', substr($_, 0, 4));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜