sub big_money{
1 my $number = sprintf "%.2f", shift @_;
2 #add one comma each time through the do-nothing loop
3 1 while $number =~ s/^(-?\d+)(\d\d\d)/$1,$2/;
4 # Put the dollar sign in the right place
5 $number =~ s/^(-?)/$1\$/;
6 $number;
}
注解:$number=12345678.9,则经过 sprintf 得到12345678.90,然后第3行代码第一次迭代替换为12345,678.90,第二次迭代为12,345,678,90,最后第5行得到$12,345,678,90。这里不能使用/g modifier 去做全局搜索-替代,因为是从后向前进行操作,而不是从前向后进行操作。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/24104518/viewspace-722061/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/24104518/viewspace-722061/
本文介绍了一种在Perl编程语言中实现货币格式化的方法。通过使用正则表达式逐步添加逗号作为千位分隔符,并正确放置美元符号,实现了数值到标准货币格式的转换。注意此过程不采用全局搜索替换,以确保从右至左处理数据。
499

被折叠的 条评论
为什么被折叠?



