|
Perl - a list or a hash?
You can hold multiple scalars in either a list or a hash in Perl. A list (signaled by an @ character or [..] around the subscript) is ordered - i.e. the elements are numbered and the order is significant. In contrast, a hash (signalled by a % character or {..} around the subscript) is unordered; the elements are named and the order isn't easily predicted.
Why would anyone want to use a hash if it's not in order? Well - if you want to look things up based on a key it's very easy and very efficient. And if you've keyed data and use lists, it's quite awkward to write the code to keep them in step. Here's an example:
# Using a list - works but bulky
@onco = ("Nathan","Steve","Andrew");
@from = ("London","Romford","Cardiff");
print "Where is ... from ? ";
chop ($name = <STDIN>);
for ($k=0; $k<@onco; $k++) {
if ($onco[$k] eq $name) {
print "$name is from $from[$k]\n";
}
}
# Using a hash - an unordered collection
%pep_tab = ("Nathan" => "Brighton",
"Steve" => "Walthamstow",
"Andrew" => "London");
print "Where is ... from ? ";
chop ($name = <STDIN>);
print "$name was from $pep_tab{$name}\n";
It turns out that hashes have many, many other uses too - their very quick look up algorithm is great for anything from checking for a word in a dictionary through to analysing all the client computers registed in your web access log. (written 2006-12-06 18:02:28)
Associated topics are indexed under P208 - Perl - ListsP211 - Perl - Hashes
Some other Articles
Both one team and twoWiltshire letterboxesString duplication - x in Perl, * in Python and RubyPerl - $_ and @_Perl - a list or a hash?Realistic on line shoot'em upCSL, KISS and RTFMKISS - one action per statement please - PerlPractical polymorphism in actionGeorge Hotel and Well House Manor, Melksham
|
2259 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|