職案人

求職・歴史・仏教などについて掲載するつもりだが、自分の思いつきが多いブログだよ。適当に付き合って下さい。

「printf」関数と「sprintf」関数の違い

2018年01月27日 | perl
「printf」関数と「sprintf」関数の違い

【環境条件】
Eclipse 4.4(ルナ)
XAMPP 1.8.3 
Perlは既にインストール済み

【文字列を指定のフォーマット】
1)フォーマット
printf関数→指定のファイルハンドルに対して整形した結果の文字列を出力
sprintf関数→整形した結果を文字列として返す

2)書式
printf([ファイルハンドル] 書式指定文字列, リスト);
戻り値 = sprintf(書式指定文字列, リスト);

サンプル「test01.pl」
use strict;
use warnings;
printf("番号は %03d です\n", 24);%はフォーマット指定子
・結果
番号は 024 です

3)フォーマット指定子
%[フラグ][最小幅][.精度/最大幅]型指定子
「%03d」→対応する値を「10進数の数値で幅を3桁にし0詰めにする」

サンプル「test01.pl」
use strict;
use warnings;
printf("Aは %03d 円、Bは %03d 円です\n", 30, 80);
・結果
Aは 030 円、Bは 080 円です

4)指定子の種類
・型指定子

・数値のデータ型以外の型指定子


5)フラグ
フラグ→フォーマット指定子のオプション
%[フラグ][最小幅][.精度/最大幅]型指定子


サンプル「test02.pl」
use strict;
use warnings;
printf("[%d]\n", 30);
printf("[% d]\n", 30);
printf("[% d]\n", -30);

printf("[%d]\n", 30);
printf("[%+d]\n", 30);
printf("[%+d]\n", -30);

printf("[%4d]\n", 30);
printf("[%-4d]\n", 30);

printf("[%4d]\n", 30);
printf("[%04d]\n", 30);

printf("[%#o]\n", 30);
printf("[%#x]\n", 30);
printf("[%#b]\n", 30);

・結果
[30]
[ 30]
[-30]
[30]
[+30]
[-30]
[ 30]
[30 ]
[ 30]
[0030]
[036]
[0x1e]
[0b11110]

6)最小幅
文字列の最小の幅を指定
%[フラグ][最小幅][.精度/最大幅]型指定子

サンプル「test03.pl」
use strict;
use warnings;
printf("[%d]\n", 30);
printf("[%5d]\n", 30);
printf("[%5d]\n", -30);
printf("[%-5d]\n", -30);
printf("[%#o]\n", 30);
printf("[%#5o]\n", 30);
printf("[%#x]\n", 30);
printf("[%#5x]\n", 30);
printf("[%#b]\n", 2);
printf("[%#5b]\n", 2);
printf("[%15e]\n", 12.3);
printf("[%15f]\n", 12.3);
printf("[%3d]\n", 760128);

・結果
[30]
[ 30]
[ -30]
[-30 ]
[036]
[ 036]
[0x1e]
[ 0x1e]
[0b10]
[ 0b10]
[ 1.230000e+001]
[ 12.300000]
[760128]

7)精度/最大幅
浮動小数点数に対して精度を指定した場合は、小数点以下の桁数となる。
%[フラグ][最小幅][.精度/最大幅]型指定子

サンプル「test04.pl」
use strict;
use warnings;
printf("%f\n", 0.012);
printf("%.4f\n", 0.012);
printf("%e\n", 0.012);
printf("%.3e\n", 0.012);

printf("[%.4d]\n", 123);
printf("[%.6d]\n", 123);
printf("[%8.6d]\n", 123);

printf("[%.6x]\n", 123);
printf("[%#.6x]\n", 123);

printf("[%s]\n", "Javascript");
printf("[%.5s]\n", "Javascript");

・結果
0.012000
0.0120
1.200000e-002
1.200e-002
[0123]
[000123]
[ 000123]
[00007b]
[0x00007b]
[Javascript]
[Javas]

8)精度/最大幅の桁数を値で指定
printf("[%.*d]¥n", 6, 123);

サンプル「test05.pl」
use strict;
use warnings;
printf("[%.6d]\n", 123);
#桁数を直接、値で指定
printf("[%.*d]\n", 6, 123);
printf("[%s] [%.*s] \n", "Hello", 3, "Hello");

・結果
[000123]
[000123]
[Hello] [Hel]

8)値をインデックス指定で使用
値のインデックスを指定することで、任意の位置の値を使用する方法を確認します
・書式
printf(" A=%2¥$d, B=%1¥$d¥n", 123, 456);

サンプル「test06.pl」
use strict;
use warnings;
printf(" A=%d, B=%d\n", 123, 456);
printf(" A=%2\$d, B=%1\$d\n", 123, 456);
printf(" A=%2\$d, B=%2\$d\n", 123, 456);
printf("%2\$d, %d, %1\$d, %d\n", 123, 456);

・結果
A=123, B=456
A=456, B=123
A=456, B=456
456, 123, 123, 456
コメント    この記事についてブログを書く
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする
« perlとサブルーチン | トップ | ファイル操作 »
最新の画像もっと見る

コメントを投稿

perl」カテゴリの最新記事