open.itworld.com
  Search  
Security Home Page Security Webcasts Security White Papers Security Newsletters Security News Open Topics Careers ITworld Voices ITwhirled The Security site of ITworld.com

Unix Tip: Using associative arrays in the Korn shell and Perl

ITworld.com 08/16/2006

Sandra Henry-Stocker, ITworld.com

Send in your Unix questions today! | See additional Unix tips and tricks

An associative array is an array which uses strings as indices instead of integers. To see how associative arrays work, we're going to look at both the Korn shell and Perl, though only the newest version of the Korn shell (referred to as "korn93") supports associative arrays.

Carrying on with our rainbow colors example from last week, we need to associate some aspect of rainbow colors with the color names to demonstrate how associative arrays work. So, in the examples below, I have associated the wavelength of each rainbow color with its name.

First, the Korn shell:

To define an associative array in the Korn shell, we use the command "typeset -A" followed by the name of the array we are creating.

> typeset -A wavelength
Once this is done, we can start assigning elements to the array. We can do this one at a time as shown below or in one long parenthesized statement as shown in the examples below.

One at a time:
> wavelength["red"]=650
> wavelength["orange"]=590
> wavelength["yellow"]=570
> wavelength["green"]=510
> wavelength["blue"]=475
> wavelength["indigo"]=445
> wavelength["violet"]=400
In one parenthesized statement:
> typeset -A wavelength
> wavelength=([red]=650
>             [orange]=590
>             [green]=510
>             [blue]=475
>             [indigo]=445
>             [violet]=400)
The spacing shown above for the second syntax is not required. I only did this to make the example more clear.

To print an element from our wavelength array, we can use this syntax:
> print "The wavelength of green is ${wavelength[indigo]) nm"
The wavelength of green is 510 nm
We can demonstrate that our associative array has captured all of the assigned values by printing the entire array at once using the command shown below:
> print ${wavelength[@]}
475 400 590 510 650 570 445
Notice the odd order in which the wavelengths are listed. This neither corresponds to the order of the numeric values or the color names.

The Perl syntax for defining an associative array (also known as a "hash") is very similar to the Korn syntax:
%wavelength = ("red", 650,
        "orange", 590,
        "yellow", 570,
        "green", 510,
        "blue", 475,
        "indigo", 445,
        "violet", 400);
Now, let's print the wavelength associated with one of our colors:
print "The wavelength of indigo is $wavelength{'indigo'} nm\n";
The wavelength of indigo is 445 nm
To print the entire array using Perl, you would use this syntax:
print %wavelength;
Your output would look like this:
blue475green510indigo445violet400red650yellow570orange590
Notice how different this output looks than the Korn output shown above. This points to a fundamental difference in the way that associative arrays are implemented in the two scripting languages. In Perl, every other array element is actually the index value.

If you run into errors using associative arrays in Perl that tell you that you can't use an undefined value as a symbol reference, look closely at your print statement. It is far too easy to use the wrong characters when copying an example like this. Those are braces around 'indigo' (uppercase [ and ] characters), not parentheses.

If you're not sure which version of the Korn shell you are using, you can download the shtype script from shelldorado.

If you're running korn93, your output will look like this:
> ./shtype
KSH93 Version M 1993-12-28 r
The shtype script deduces this by determining whether your shell can extract substrings from a variable. Korn93 can do this. Korn89 cannot.

If you'd like to try Korn93, you can download ksh93 source or binary packages here.

Rainbow Science

To ensure that the examples in this column make sense, I should point out that the numbers in our wavelength arrays refer to nanometers. For example, the wavelength of the color violet is roughly 400 nanometers. Of course, that's exceedingly tiny. One million nanometers is only 39.4 inches. So be careful not to capitalize the "nm" abbreviation if you use any of these array examples or you'll be referring to nautical miles!

Also, just to be sure that I'm not misleading you, understand that the colors in rainbows include, but are not limited to, the colors listed. Rainbows actually cover the visible light wavelength range of 400-700 nanometers. We people tend to pick out discrete colors and name them, but rainbows aren't really composed of a series of solid stripes, but a gradually changing hue that moves from red to violet and includes all wavelengths in between.

Sandra Henry-Stocker has been administering Unix systems for more than 18 years. She describes herself as "USL" (Unix as a second language) but remembers enough English to write books and buy groceries. She currently works for TeleCommunication Systems, a wireless communications company, in Annapolis, Maryland, where no one else necessarily shares any of her opinions. She lives with her second family on a small farm on Maryland's Eastern Shore. Send comments and suggestions to bugfarm@gmail.com.




Sponsored Links

Sign up for a Microsoft Dynamics® CRM WEBCAST
Hear globally recognized leaders in customer strategy discuss the importance and evolution of CRM.
Sun Microsystems' - FREE 60 DAY TRIAL OFFER!
Test Sun's Newest Servers BEFORE YOU BUY. Plug Them In With Access To Full Technical Support.
100% Web Based Help Desk Software
Easy to use, customizable to meet your needs, powerful and scalable. Free online demo. Try it today!
Sign up for a Microsoft Dynamics® CRM WEBCAST
Hear globally recognized leaders in customer strategy discuss the importance and evolution of CRM.
Used and Refurbished HP ProCurve Switches
Lifetime Warranties, Professional Testing & Shipping on all HP Equipment Purchases!
» Buy a link now

Advertisements
Sponsored links
Locate Hidden Software on business PCs with this free tool
Bring harmony to your mix of UNIX-Linux-Windows computing environments
Top 5 Reasons to Combine App Performance and Security
KODAK i1400 Series Scanners stand up to the challenge
 Home   Open source  Operating systems  Unix
www.itworld.com    open.itworld.com     security.itworld.com     smallbusiness.itworld.com
storage.itworld.com     utilitycomputing.itworld.com     wireless.itworld.com

 
Contact Us   About Us   Privacy Policy    Terms of Service   Reprints  

CIO   Computerworld   CSO   GamePro   Games.net   IDG Connect   IDG World Expo   Infoworld   ITworld   JavaWorld   LinuxWorld  MacUser   Macworld   Network World   PC World   Playlist  

Copyright © Computerworld, Inc. All rights reserved

Reproduction in whole or in part in any form or medium without express written permission of Computerworld Inc. is prohibited. Computerworld and Computerworld.com and the respective logos are trademarks of International Data Group Inc.