Loginskip to content

October 30th, 2006

instead of vegetables the program would still run, but

keys you wish to use to the indices of the values in the array. This is much easier to understand with an example: [6] As of perl version 5.005_03. It is not only new, it’s experimental, so check the documentation for any version of Perl later than 5.6.0 that you have to see if it’s still in there. It appears from the latest discussions that it is unlikely to survive to Perl 6; however, being able to create hashes whose keys are fixed is so useful that the capability to do this is likely to persist in some form. $sound = [ { dog => 1, cat => 2, bird => 3}, ‘bark’, ‘meow’, ‘tweet’ ]; You must ensure that the numbers that are the values in the anonymous hash correspond to the positions of the corresponding values, but now you can say $sound->{dog} to yield ‘bark’. You could also get at it with $sound->[1], but that’s missing the point of a pseudo-hash. What you can’t do is put a new key in the pseudo-hash in this fashion: $sound->{frog} = ‘ribbit’; because that will generate an error (putting a new key in the pseudo-hash is possible but harder than that). But if your application doesn’t require inserting new keys at run time, this feature of the pseudo-hash will ensure that you are instantly alerted if you mistype a key. Because pseudo-hashes have an uncertain future, we won’t make a Perl of Wisdom out of them just yet. Evaluate the benefits of using them on a case-by-case basis. We have been making a more general point here that is worth a Perl of Wisdom: Force as many errors as possible to occur at compile time rather than at run time. This little program can be bulletproofed even further. It still requires the repetition of the keys vegetables and fruit in the pseudo-hashes and input recognition loop. If we could bind them together somehow, we’d have less of a chance of coming up with a compile-time error. Enter our latest revision. Here we’ve done some more radical surgery. You’ll notice that we’ve removed the need to refer to the hash keys while going around the input loop by creating the single hash %food_type to map from an inventory item to a vegetable or fruit. 1 use fields; 2 $_ = fields::phash(vegetables => 0, fruit => 0) 3 for my ($cases_bought, my $cases_sold); 4 my %food_type = (map ({ ($_, ‘vegetables’) } 5 qw(carrots broccoli kale spinach leeks)), 6 map { ($_, ‘fruit’) } 7 qw(apples kumquats pears bananas kiwis) 8 ); 9 while (<>) 10 { 11 my ($food, $bought, $sold) = split; 12 if (my $type = $food_type{$food}) 13 { 14 $cases_bought->{$type} += $bought;
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services

Comments are closed.