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博客 ” ,链接:https://blog.itpub.net/24104518/viewspace-722061/
,如需转载,请注明出处,否则将追究法律责任。