Search This Blog

Sunday, February 13, 2011

Does PowerShell have something similar to the Perl abbrev() function

Programmer Question

So in Perl, there is a function call abbrev() that given a list of keywords, returns a hash mapping all the minimally abbreviations to their keyword:



@keywords = {"this", "and", "that"}
%AbbevList = abbrev(@keywords);


This would return a Hash like this:



thi => "this"
this => "this"
tha => "that"
that => "that"
a => "and"
an => "and"
and => "and"


In Perl, this allowed me to take user abbreviations for my keywords and easily map them correctly to the "real" keyword as long as the user's input was minimally unique.



Does PowerShell have anything similar?



Find the answer here

1 comment:

  1. None that I know of. Here is my attempt to write my own:
    function New-AbbrevHashTable {
    param (
    [Parameter(Mandatory = $true)]
    [string[]]$Keys
    )
    $ReturnHash = @{}
    foreach ($Key in $Keys) {
    for ($i = 0; $i -lt $Key.Length; $i++) {
    $Sub = $Key.Length - $i
    $Abbrev = $Key.Substring(0,$Sub)
    if ( ($Keys -like "$Abbrev*").Count -eq 1) {
    $ReturnHash.$Abbrev = $Key
    }
    }
    }
    if ($ReturnHash) {
    $ReturnHash
    } else {
    Write-Warning 'No abbrev-able keys found'
    }
    }

    New-Alias abbrev New-AbbrevHashTable

    ReplyDelete

Related Posts with Thumbnails