3桁ごとにカンマで区切る

30分プログラム、その626。3桁ごとにカンマで区切ってみよう。
長い整数って読みづらいじゃないですか。そこで、整数を与えると3桁ごとにカンマを挿入して文字列化してくれる関数を書いてみよう。

C#だとstring.Format("{0:#,#}",123456789)でできちゃうらしいけど、あえて自力でやってみるのもいいものです。

使い方

print sep_by_comma(123456789),"\n"; # 123,456,789

# 区切り文字を与えることもできる
print sep_by_comma(123456789,'_'),"\n"; # 123_456_789

ソースコード

#! /usr/bin/perl
# -*- mode:perl; coding:utf-8 -*-
#
# comma.pl -
#
# Copyright(C) 2009 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2009/07/25 21:32:29
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#


use strict;
use warnings;
use Data::Dumper;
use integer;;

sub sep_by_comma($;$){
    my ($n,$sep) = @_;
    $sep ||= ',';
    if($n < 1000){
	sprintf "%d",$n;
    }else{
	&sep_by_comma($n/1000,$sep) . $sep . $n % 1000
    }
}

print Dumper(sep_by_comma(123456789));
print Dumper(sep_by_comma(123456789,'_'));