Loginskip to content

October 30th, 2006

instead of vegetables the program would still run, but

instead of vegetables the program would still run, but it would not produce correct output.[5] [5] It would generate a warning, courtesy of -w, in line 26 when we went to print a nonexistent hash entry, unless we were lucky enough to have mistyped vegetable in both places. Don’t enter the same text in different places in a program and depend on having to keep them in sync. Or at the very least, we would like the code to refuse to run if we did make such a typo. Perl 5.005 provides a new datatype the pseudo-hash which we can use here to accomplish that. In the following listing, it appears that little has changed structurally. But if you commit the typos we just discussed, instead of running, Perl instead spits out the error: No such array field at greengrocer.pl line 16, <> chunk 1 even if we misspell vegetables in the same way on both line 11 and line 21. 1 my $cases_bought = [{vegetables => 1, fruit => 2}, 0, 0]; 2 my $cases_sold = [{vegetables => 1, fruit => 2}, 0, 0]; 3 my %vegetable = map { ($_, 1) } qw(carrots broccoli 4 kale spinach leeks); 5 my %fruit = map { ($_, 1) } qw(apples kumquats 6 pears bananas kiwis); 7 while (<>) 8 { 9 my ($food, $bought, $sold) = split; 10 my $type; 11 if (exists $vegetable{$food}) { $type = ‘vegetables’ } 12 elsif (exists $fruit{$food}) { $type = ‘fruit’ } 13 else { warn “I don’t know the food type $foodn” } 14 if (defined $type) 15 { 16 $cases_bought->{$type} += $bought; 17 $cases_sold->{$type} += $sold; 18 } 19 } 20 21 foreach my $type (qw(fruit vegetables)) 22 { 23 print $cases_bought->{$type} - $cases_sold->{$type}, 24 ” cases of $type on handn”; 25 } A pseudo-hash bears some explanation, since it’s so new.[6] If the first element of an array is a reference to a hash, the other elements of that array can be accessed not just by their indices, but by using a reference to the array as though it were a hash reference whose keys were taken from that first element. The hash referenced by the first element must map the
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.