-
Notifications
You must be signed in to change notification settings - Fork 8.2k
Support a foreach statement with implicit iteration variable $_ for consistency with the ForEach-Object cmdlet #3830
Copy link
Copy link
Closed
Labels
Committee-ReviewedPS-Committee has reviewed this and made a decisionPS-Committee has reviewed this and made a decisionIssue-Enhancementthe issue is more of a feature request than a bugthe issue is more of a feature request than a bugResolution-Won't FixThe issue won't be fixed, possibly due to compatibility reason.The issue won't be fixed, possibly due to compatibility reason.WG-Languageparser, language semanticsparser, language semantics
Description
Inspired by #3695.
The builtin foreach alias for the ForEach-Object cmdlet keeps causing confusion with the foreach statement.
Given that the cmdlet and the statement are conceptually analogous, perhaps one way to mitigate the confusion is to allow the foreach statement to have an implied iteration variable, namely $_, just as when using ForEach-Object.
Desired behavior
# This works currently: an *explicit* iteration variable is needed.
> foreach ($suffix in 1, 2, 3) { "A" + $suffix }
A1
A2
A3
# Wishful thinking: allow *omitting* an iteration variable to use $_ by default,
# as in a pipeline, which would be the equivalent of:
# 1, 2, 3 | ForEach-Object { "A" + $_ }
> foreach (1, 2, 3) { "A" + $_ }
A1
A2
A3Currently, one is forced to choose between:
-
more concise, but decidedly slower pipeline syntax:
1, 2, 3 | ForEach-Object { "A" + $_ } -
faster, but more verbose
foreachsyntax:foreach($suffix in 1, 2, 3) { "A" + $suffix }
The suggested foreach syntax evens the playing field and allows a solution that is both concise and performant.
PowerShell Core v6.0.0-beta (v6.0.0-beta.1) Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
Committee-ReviewedPS-Committee has reviewed this and made a decisionPS-Committee has reviewed this and made a decisionIssue-Enhancementthe issue is more of a feature request than a bugthe issue is more of a feature request than a bugResolution-Won't FixThe issue won't be fixed, possibly due to compatibility reason.The issue won't be fixed, possibly due to compatibility reason.WG-Languageparser, language semanticsparser, language semantics