4 ms·
> WTF were they thinking when they decided it was useful when the result of a function is an array of every statement result within that function? Because in a
by ygra 10y ago
> WTF were they thinking when they decided it was useful when the result of a function is an array of every statement result within that function?
Because in a pipeline results are usually »whatever the element happens to have as its output«. Usually you know or notice if statements within your function have return values or not. I haven't found it problematic so far, either. You don't write PowerShell like C# anyway, so different patterns are idiomatic. You'll get the hang of it fairly quickly.
> And why isn't there a useful way (like, say, "return") that overrides that behaviour?
There is. It's called return:
return (expr)
is the same as
(expr)
return
and return will immediately exit the function / script block.
> Automatic unboxing and splatting of arrays.
Admittedly, this can be annoying, however this only ever applies to function or cmdlet output. When you're creating a one-element array (via @(1) or ,1) it stays that way unless used as the first part in a pipeline, where unwrapping is usually wanted.
You can also use Count instead of Length (unless your items have a Count property) since v3, as PowerShell implicitly understands reading the Count property on a scalar value that doesn't have it and returns 1.
The usual fix is to explicitly make the return value an array, though:
$foo = @(Get-Foo)
PowerShell cannot know that a call results in multiple values or just one, e.g. Get-Service yields an array, but Get-Service foo yields a single object. It's not unreasonable to expect something like (Get-Service foo).DisplayName to work instead of having to do either (Get-Service foo)[0].DisplayName or Get-Service foo | % DisplayName.
So it's a trade-off between two ugly things. Trade-offs are always bound to annoy people who consider one thing worse than the other.
> Still, Get-Unique is always case sensitive, as is Select-Object -Unique. Of course, you can get case insensitive uniqueness by using Sort-Object -Unique.
Huh, learned something new there, thanks. I think the only instances where I needed unique strings was in golfing, so sort -u was the way to go anyway. At least it's documented in each of those cases.
As for sorting using the .NET method not adhering to the defaults used throughout PowerShell, I think that's hardly surprising. You're explicitly leaving PowerShell and using the BCL directly. Of course other rules apply. And there are even worse annoyances on that front, such as that PowerShell's current directory is not the process' current directory (so you can't really use relative paths with .NET APIs).
> -AsString
Never used, to be honest, so no opinion here.
- tremon 10y agoThere is. It's called return I know. Just to be sure, my beef is that: function test() { 1 return 2 } still returns @(1,2), not just 2