0
0

More than 5 years have passed since last update.

Perlのprintf/sprintfの複数の引数の幅を変数で設定する

Posted at

初記事。

やりたいこと

2つの配列で2重ループを回して、適当な処理後に各ループで結果を出力する。
出力を整形する際、各配列で最大長の要素の幅で整形したい。わざわざ2回sprintf書いて連結するのはちょっと嫌だ。

perldoc.jpによれば %*s のようにアスタリスクで埋めれば後の引数で幅を指定できるようである。ただし複数引数ある時の挙動は書いてないように見える。

試した

perl
use strict;
my @Arr1=("AAA","BB");
my @Arr2=("X","YY","ZZZZ");

my $max1=0;
$max1=length($_)>$max1?length($_):$max1 for (@Arr1);
my $max2=0;
$max2=length($_)>$max2?length($_):$max2 for (@Arr2);

for my$i(@Arr1){
    for my$j(@Arr2){
        printf('%s %*s %s %*s %s'."\n","12",$max1,$i,"34",$max2,$j,"56");
    }
}

出力はこんな感じになる。

12 AAA 34    X 56
12 AAA 34   YY 56
12 AAA 34 ZZZZ 56
12  BB 34    X 56
12  BB 34   YY 56
12  BB 34 ZZZZ 56

結論

printf("... %*s ...", ... ,$width,$content, ... );

%*2$x のようにすることで参照引数の位置を固定できる。が、出力を色々追加したくなった時に事故起こしそうである、シングルクォーテーションのために改行文字の扱いが面倒になる、ので採用しなかった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0