Loginskip to content

October 30th, 2006

What’s a symbolic reference? It’s when a scalar

This kind of code is very common from a programmer who is happy to have identified the identical nature of the different sets of fruitand vegetablevariables and abstracted their use to a degree that they can be summed with the same code. However, the symbolic references are not necessary: not only do they break use strict, but they do not work with lexical variables, which is why this program doesn’t have any mykeywords. Well, that doesn’t sit right with Perl of Wisdom #8, so we should look for a way to write this program without dynamic variables. We don’t have to look far. Whenever you are tempted to create parallel variable sets, use instead a hash whose keys are the portion of your variable names that changes. Here’s the new program: 1 my %cases_bought = (fruit => 0, vegetables => 0); 2 my %cases_sold = (fruit => 0, vegetables => 0); 3 my %vegetable = map { ($_, 1) } 4 qw(carrots broccoli kale spinach leeks); 5 my %fruit = map { ($_, 1) } 6 qw(apples kumquats pears bananas kiwis); 7 8 while (<>) 9 { 10 my ($food, $bought, $sold) = split; 11 my $type; 12 13 if (exists $vegetable{$food}) { $type = ‘vegetables’ } 14 elsif (exists $fruit{$food}) { $type = ‘fruit’ } 15 else { warn “I don’t know the food type $foodn” } 16 17 if (defined $type) 18 { 19 $cases_bought{$type} += $bought; 20 $cases_sold{$type} += $sold; 21 } 22 } 23 24 foreach my $type (qw(fruit vegetables)) 25 { 26 print $cases_bought{$type} - $cases_sold{$type}, 27 ” cases of $type on handn”; 28 } Now, if it looks obvious to you that this first example should be using a hash, be aware that it is easier to fall into this trap than you might think, especially when you have a large program with a bunch of hitherto disparate variables that you suddenly realize can be treated similarly. Is this the best way to code this program? Hardly. We are repeating keys explicitly in two places where a typo would cause a problem. If we mistyped the strings in the $typeassignment or the foreach and it would be a natural mistake to type vegetable
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services

Comments are closed.