Skip to content

String cgt #18638

Closed
Closed

Description

@lbj2014

Prerequisites

Steps to reproduce

because of ascii, "A"==65, "a"==97

Write-Host ([char]"A" -cgt [char]"a") # False
Write-Host ([int][char]"A" -gt [int][char]"a") # False

but

Write-Host ("A" -cgt "a") # True

can tell me why

Expected behavior

Write-Host ("A" -cgt "a")
False

Actual behavior

Write-Host ("A" -cgt "a")
True

Error details

No response

Environment data

Name                           Value
----                           -----
PSVersion                      7.3.0
PSEdition                      Core
GitCommitId                    7.3.0
OS                             Darwin 21.6.0 Darwin Kernel Version 21.6.0: Wed Aug 10 14:28:23 PDT 2022; root:xnu-8020.141.5~2/RELEASE_ARM64_T6…
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Visuals

No response

Activity

  1. added
    Needs-Triage
    on Nov 22, 2022
  2. jhoneill commented on Nov 22, 2022

    @jhoneill

    It is more complicated than the ASCII values.

    Consider A À Å ; a à and å

    In English A À Å all sort together even though US 7-bit ASCII doesn't include accented characters and Unicode must maintain compatibility so the A+Accent isn't near A

    In Norwegian Å is treated as a distinct letter. so in English

    l> "a", "b" , "y", "å", "z", "Z,", "Å", "Y", "B", "A" | sort-object
    a
    A
    å
    Å
    b
    B
    y
    Y
    z
    Z,
    

    The accented characters sort on their own, with the unaccented character. But change the culture...

    PS> "a", "b" , "y", "å", "z", "Z,", "Å", "Y", "B", "A" | sort-object -Culture no-no
    a
    A
    b
    B
    y
    Y
    z
    Z,
    å
    Å
    

    The culture basically dictates if we sort upper before lowercase or lower before upper case, and I think most are upper-last / lower-first

    Greater than and less than then work on where the character would be sorted , not on its unicode value (because if you we used 8 bit encodings, some characters like € might not have a value or might have different values depending on the active code page. ASCII, being for American in the 1950s doesn't have €)

    a sorts before A so is "less than" even though [int]"a" is greater than [int]"A" .

    b sorts after "À" (but before "B") so

     ps > [int][char]"b" -lt [int][char]"À"
    True
    
    ps> "b" -lt "À"
    False 
    

    .

  3. daxian-dbw commented on Nov 23, 2022

    @daxian-dbw
    Member

    A TL;DR answer that supplement James O'Neill (@jhoneill)'s answer above is:

    • for string operands, -cgt eventually comes down to the .NET method Cultureinfo.CompareInfo.Compare("A", "a", CompareOptions.None), and the cultureInfo used in PoweShell is InvariantCulture. The return value is 1 in this case, and that's why "A" -cgt "a" returns true.
  4. added
    Resolution-Answered
    and removed
    Needs-Triage
    on Nov 23, 2022
  5. mklement0 commented on Nov 24, 2022

    @mklement0
    Contributor

    Let me try a comprehensive summary:

    • Terminology:

      • The .NET equivalent of ASCII values - which are limited to the legacy 7-bit ASCII "alphabet" (limited to 128 characters) - are Unicode code points, because .NET [string]s are Unicode strings, composed of [char] instances, which are UTF-16 code units, i.e. in effect [uint16] values, which therefore have a range of 0x0 - 65535 (0xFFFF); Unicode's code points are a superset of ASCII values, however.

        • Note that, despite their name, [char] instances are only typically, but not always whole characters, namely only for those code points in the so-called BMP (Basic Multilingual Plane); for characters outside that plane, i.e. those with a code point above 65535 (0xFFFF), which notably includes emojj, they form either half of a surrogate pair; that is, two [char] instances are needed to represent a character outside the BMP.
      • In practice, when strings are compared in a manner that requires ordering (less-than, equal, or greater-than), a linguistic (human-language-based), culture-specific collation order is often used (though the .NET APIs don't use that term) - and such an order is unrelated to (Unicode) code points.

        • Usually, corresponding lowercase and uppercase letters are grouped together, with lowercase letters coming before their uppercase counterparts, and with accented variants often, but not necessarily, being grouped with their base characters, as James O'Neill (@jhoneill)'s examples show (add -CaseSensitive for predictable results).

        • In .NET, these culture-specific rules are implemented via per-culture implementations of the System.Globalization.CompareInfo class.

      • By contrast, comparing strings purely numerically by their characters' code points is called an ordinal comparison.

    • PowerShell compares [string] instances using a culture-specific collation order, i.e. it does not perform ordinal comparison.

      • As Dongbo Wang (@daxian-dbw) points out, PowerShell's operators use the invariant culture, [cultureinfo]::InvariantCulture

      • By contrast, Sort-Object uses the current culture ([cultureinfo]::CurrentCulture, as also returned by Get-Culture).

      • This discrepancy is unfortunate, and can make a difference, as James O'Neill (@jhoneill)'s examples show (add -CaseSensitive for predictable results). Unfortunately, as of v7.3.0, requesting the invariant culture via -Culture ([cultureinfo]::InvariantCulture) does not work: see Sort-Object, unlike operators, uses the current culture and doesn't support requesting the invariant culture via -Culture #18655

      • If you want ordinal comparison:

        • For two given strings, use [string]::Compare() with an ordinal System.StringComparison value, e.g.:
          • [string]::Compare('a', 'A', [StringComparison]::Ordinal) ... 32, i.e., the difference in code-point values; that the number is positive implies that a is greater than A, in an ordinal sense.
          • [string]::Compare('a', 'A', [StringComparison]::OrdinalIgnoreCase) ... 0, because - after culture-invariant transformation of both input strings to uppercase - their code points are identical.
        • For sorting, Sort-Object does not offer a solution, because the only way to fundamentally modify the sort order is with a -Culture argument, and there isn't a culture that that performs ordinal comparisons.
          • However, the System.Array type has a static Sort() method with an overload that accepts a System.Collections.IComparer instance, to which you can pass a System.StringComparer instance - note that this method sorts in place:
            • $a = 'a', 'A'; [Array]::Sort($a, [StringComparer]::Ordinal); $a # -> 'A', 'a', i.e. ordinal sorting took place.
    • By contrast, [char] instances always use (ultimately) ordinal comparison; note that PowerShell always requires a [char] cast, even with single-character string literals such as 'a', given that PowerShell has no built-in literal syntax for [char] (unlike C#, where '.<some-char>' is exclusively a char literal):

      • For (non-)equality comparison (-eq, -ne), case is respected, if requested:
      • For less-than(-or-equal) / greater-than (-or-equal) comparisons, case is ignored, because ordinal comparison is invariably performed:
        • [char] 'a' -cgt [char] 'A' -> $true, because the code point of char. a (LATIN SMALL LETTER A, U+0061) is greater than the code point of A (LATIN CAPITAL LETTER A, U+0041)
        • [char] 'a' -gt [char] 'A'-> !! ditto (also with -igt); that is, requests to ignore case are not honored.
      • This surprising inconsistency is arguably a bug: see Comparison operators handle [char] instances inconsistently #18659
  6. jhoneill commented on Nov 24, 2022

    @jhoneill
    • [char] 'a' -gt [char] 'A'-> !! ditto (also with -igt); that is, requests to ignore case are not honored.

    Michael Klement (@mklement0) (a hat tip to your thoroughness, although you must be neglecting other things in life :-) this looks like a bug to me

    PS>  [char] 'a' -igt [char] 'A'
    True
    
    PS>  [char] 'a' -ieq [char] 'A'
    True
    

    The above is plain wrong, either it is greater than or it is equal to. Both can't be true. (quantum joke are left as an exercise for the reader)

    I don't know if char comparisons should always be case insensitive but different behaviour between eq and ge/gt/le/lt must be wrong. If culture is addressed (with a "legacy behaviour" option) this should be addressed at the same time. Some subtle bugs could be created where code unwittingly relies on those on current behaviour, so any change probably should be opt in.

    Do we know if this has been flagged before ?

  7. mklement0 commented on Nov 24, 2022

    @mklement0
    Contributor

    Thanks, James O'Neill (@jhoneill); I agree that it is a bug, and I've created #18659

    (I've also updated the previous comment, which indeed took me a while to write, but I wanted to have a systematic overview, including for my own notes; I may reuse parts in future Stack Overflow answers)

    Note that PowerShell predominantly uses the invariant culture (operators, casts, string interpolation), and, from that vantage point, it is cmdlets that use the current culture (by default) that amount to an inconsistency.
    I think Select-String is another example.

    Unless there is a good reason for this bifurcation that I am missing.

  8. ghost closed this as completedon Nov 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution-Answered

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions