Skip to Content
Perl语言入门(第8版)
book

Perl语言入门(第8版)

by Randal L. Schwartz, brian d foy, Tom Phoenix
October 2022
Beginner to intermediate
390 pages
7h 5m
Chinese
Southeast University Press
Content preview from Perl语言入门(第8版)
260
14
到,格式字符串(即
sprintf
函数的第一个参数)在格式化某些数字前加上
0
,这种
用法我们在第
5
章介绍
printf
时并未提及。格式化定义中数字字段的前置
0
表示必要
时会在数字前补
0
以符合指定的宽度要求。如果没有前置
0
,那么日期与时间字符串里
的数字就不会用
0
补足宽度,而只留下相应长度的空格,比如
"2038/ 1/19 3
:
0
:
8"
sprintf
格式化金额数字
sprintf
的常见用法是格式化小数点后具有特定精度的数字,比如要把
2.49997
这个
金额显示成
2.50
,而不是
2.5
,我们可以使用
"%.2f"
这个格式来轻松完成格式化:
my $money = sprintf "%.2f", 2.49997;
四舍五入能够使得数字精简并且易读,但绝大多数情况下应该保留原始数据的精度,
只在输出时做四舍五入。
如果手头有个财务数据非常大,需要使用逗号来分隔才方便阅读,那么下面这个子程
序能提供很多便利:
sub big_money {
my $number = sprintf "%.2f", shift @_;
#
下面的循环中,每次匹配到的合适位置加一个逗号
1 while $number =
~
s/^(-?\d+)(\d\d\d)/$1,$2/;
#
在正确的位置补上美元符号
$number =
~
s/^(-?)/$1\$/;
$number;
}
这个子程序用了一些前面没见过的技巧,但不难推测其含义。子程序的第一行是在对
第一个(也是唯一的)参数进行格式化,让它在小数点之后刚好有两位数字。也就是 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Go程序设计语言

Go程序设计语言

艾伦A. A.多诺万, 布莱恩W. 柯尼汉
Perl语言入门

Perl语言入门

Randal L. Schwartz, brian d foy, Tom Phoenix

Publisher Resources

ISBN: 9787576602036