4

An "it works -- but is it a best practice?" question. In Perl there's a compact way of keeping track of occurrences of, say, strings found within a file: store them in a hash table. For example:

$HashTable{'the string in question'}++;


Perl increments the value for key the string in question as many times as this is done. It ensures unique "hits" at the same time that it keeps track of occurrences. Just hacking around, I found I could do much the same with Powershell:

$HashTable['a']++ or even
$Hashtable.a++ (which kind of surprised me -- or even)
$Hashtable."this is a key"++


Ok, so it works. But is there an approach in Powershell that's considered a better practice?

1
  • Oh, nice. It didn't occur to me that that could work. Commented Nov 13, 2012 at 13:14

1 Answer 1

6

Your approach looks quite good, at least for PowerShell with its helpers for hashtables. Just keep in mind that hashtables defined as @{} are case insensitive. If you need a case sensitive hashtable then create it like New-Object System.Collections.Hashtable.

Example:

# case insensitive
$hash = @{}
$hash['a']++
$hash['A']++
$hash

'------------------------'

# case sensitive
$hash = New-Object System.Collections.Hashtable
$hash['a']++
$hash['A']++
$hash

Output:

Name                           Value
----                           -----
a                              2
------------------------
a                              1
A                              1

In C# using Dictionary<string, int> is probably a "better practice". It is also possible in PowerShell but it unlikely makes things much "better" in PowerShell.

A PowerShell-ish solution is probably use of Group-Object -NoElement. Is it a better approach or practice? I do not know. It depends on a few factors including preferences. Here is the example:

'a', 'A', 'foo', 'foo' , 'bar' | Group-Object -NoElement

Output:

Count Name
----- ----
    2 a
    2 foo
    1 bar
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer -- thanks. The for-the-newbie books I've been reading have not yet covered case-sensitivity in hash tables and that's extremely useful to know. (When I think of 'best' practice I'm thinking: clear enough to understand at first glance, consistent with the language (IOW, not some terrible hack), and maintainable.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.