Year of the Pig Revisited – the magic of QL

Richard Siddaway has a blog entry showing how to calculate the Chinese Horoscope using PowerShell. His solution uses hashtables:

## create hash table
$years = @{1=”Rat”; 2=”Ox”; 3=”Tiger”; 4=”Rabbit”; 5=”Dragon”; 6=”Snake”;
           7=”Horse”; 8=”Goat”; 9=”Monkey”; 10=”Rooster”; 11=”Dog”; 0=”Pig”}
## get the year of interest
$y = Read-Host “Enter a year between 1900 and 2100 inclusive”
$anml = ($y – 1899)%12
Write-Host $years[$anml]

This is a perfectly fine solution and a good one to help get hashtables in focus. Hashtables are super useful in scripting so if you aren’t real comfortable with them yet, you should take a few minutes to experiment and master them. That said, I’m a bad typist so I’m always looking for ways to do less typing. I noticed that index for this hash table is a number and that it started at 0. This immediately made me think of using an array instead. I then looked at all those quotes and remembered a great trick that Bruce Payette taught me:

PS> function ql {$args}
PS> ql Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog
Pig
Rat
Ox
Tiger
Rabbit
Dragon
Snake
Horse
Goat
Monkey
Rooster
Dog

What that did was to take a list of arguments (note the lack of quotes) and returns them as an array (actually a stream which gets turned into an array). You’d have to go a REALLY long way to find a function with more utility per character than this one! So now the solution looks like this:

## create hash table
$years = ql Pig Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog
## get the year of interest
$y = Read-Host “Enter a year between 1900 and 2100 inclusive”
$anml = ($y – 1899)%12
Write-Host $years[$anml]

Jeffrey Snover [MSFT]
Windows PowerShell/MMC Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx