Avoiding Agnostic Jagged Array Flattening in Powershell

孤人 提交于 2019-12-01 05:46:28
stej

There is another question that starts with the same problem: Powershell pitfalls . It looks like this is done by design.

I think if you return ,$ret instead of $ret, it should work.

Two more notes:

  • you can test, if the item is array by $item -is [array] (just because it looks more like PowerShell ;)
  • @() has effect only on items that are not arrays. If you chain @(@(@(1))), you will get an array with one int item (@(@(@(1)))[0].gettype() returns Int32).
    So, @( ,@('r', 's') ) is the same as ,@('r', 's').

I tried what stej said and it worked, using this example:

function funC([int]$numOfPairs)
{
  $ret = @()
  if($numOfPairs -eq 1)
  { $ret = ,@('r','s') }
  elseif($numOfPairs -eq 2)
  { $ret = @('r','s'),@('t','u') }
  else
  { $ret = @('r','s'),@('t','u'),@('v','w') }

  Display $ret 0 "Inside Function C ($numOfPairs)"
  return ,$ret
}


### Start Program

$z = funC 1
Display $z 0 'Return from Function C(1)'
$z = funC 2
Display $z 0 'Return from Function C(2)'
$z = funC 3
Display $z 0 'Return from Function C(3)'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!