LoginSignup
2
2

More than 5 years have passed since last update.

初期化済みの固定長二次元配列を作る。

Posted at

PowerShellの講習を受けてて、他の受講者から「固定長の二次元配列を生成、初期化するには?」みたいな質問が出てたので、考えてみた。習った範囲では...

  • 配列は基本的には固定長で、要素数の外をインデックスで指定するとエラーになる
  • インクリメント演算($array += $element)すると最後に追加されて配列長が伸びる。

...だったので、その範囲で教わった命令だけ使ってできるのはこんな感じか。

PS C:\usr\powershell> $dim=(5,3);
PS C:\usr\powershell> $myArray=@(); 0..($dim[0]-1) | %{$myArray+=$null; $myArray[-1]=@(); 0..($dim[1]-1) | %{$myArray[-1] += $null} }

%foreachの略記。$nullはNull値が入った特殊変数。
配列長を見ることで結果確認とする。

PS C:\usr\powershell> $myArray.count
5
PS C:\usr\powershell> $myArray[0].count
3

なんとなくshell芸やPerlのone liner的な変態っぽさを感じるのだけど、スクリプト環境で固定長二次元配列初期化済みというリクエストがそもそも変態っぽい気もする。あまり使い道を思いつかない。

2
2
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
2
2