What’s a symbolic reference? It’s when a scalar contains a string that names another variable, and you attempt to use that scalar as though it were a hard reference. This works, if you’re not using strict or have selectively disabled the component of use strictthat prevents it.[3] [3] You do this with the statement no strict ‘refs’. Now, in Perl 4, storing the name of a variable inside another variable was the only way to carry out certain very common tasks (and required that you also use eval). But since the advent of hard references in Perl 5, there is almost no situation in which you will need to use a symbolic reference. However, there may be many more occasions when you think that you need to. So let’s examine some of those. The program that follows is a hypothetical greengrocer’s inventory counter that reads data consisting of a fruit or vegetable and the number of cases bought and sold of that item, separated by spaces on new lines.[4] [4] Notice that we defied our own indenting style to put the if statement blocks on one line each, and left out the semicolon after their sole statements. This just goes to show that sometimes there’s no need to be a slave to style if breaking the rules buys you an advantage like greater readability. 1 $fruit_cases_bought = 0; 2 $fruit_cases_sold = 0; 3 $vegetables_cases_bought = 0; 4 $vegetables_cases_sold = 0; 5 %vegetable = map { ($_, 1) } qw(carrots broccoli 6 kale spinach leeks); 7 %fruit = map { ($_, 1) } qw(apples kumquats 8 pears bananas kiwis); 9 while () 10 { 11 ($food, $cases_bought, $cases_sold) = split; 12 if (exists $vegetable{$food}) { $type = ‘vegetable’ } 13 elsif (exists $fruit{$food}) { $type = ‘fruit’ } 14 else { warn “I don’t know the food type $foodn” } 15 16 if (defined $type) 17 { 18 ${$type.’_cases_bought’} += $cases_bought; 19 ${$type.’_cases_sold’} += $cases_sold; 20 } 21 } 22 23 print $vegetable_cases_bought - $vegetable_cases_sold, 24 ” cases of vegetables on handn”; 25 26 print $fruit_cases_bought - $fruit_cases_sold, 27 ” cases of fruit on handn”;
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
We should have used exit instead of Exit. (Perl built-in functions do not contain capital letters, and the reserved words that do are all uppercase.) Better yet, we should have called dieinstead of print. Chapter 9. Run-time Exceptions “When you have eliminated the impossible, that which remains, however improbable, must be the truth.” Sherlock Holmes in A Study in Scarlet, by Sir Arthur Conan Doyle I remember when I was writing my first program in an independently- compiled language (Fortran; before that I was just using interpreted BASIC). After much work, I got the program to compile without any errors. In glee, I turned to a co-worker and said, “All right! I’m done now!” A grin came over his face, and he said, “I doubt it.” What awaited me at that point was the evil run-time error. Perl is no slouch in the run-time error reporting department, and in fact, many errors that would occur at compile time in other languages happen at run time in Perl. For example, using a string in a numeric context: a strongly typed language would spot at compile time the attempt to assign a string to a numeric variable, but in Perl a scalar can switch between a string and a number according to whim. We present here our bug-hunting approach to resolving run-time exceptions. There’s no way to know whether you’ve gotten rid of all possible run-time bugs without running your program under every conceivable set of inputs and environmental changes that might possibly affect it.[1]
Note: If you are looking for good and quality webspace to host and run your java application check Actions java hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
[1] Aside from proofs-of-correctness; but there again, proofs-of-correctness never seem to be attached to anything longer than 10 lines anyway. The most basic run-time error is that the program refuses to execute at all. If you’ve been checking your program’s syntax with Perl’s -c switch, you might have a program that has no syntax errors but gives you the error “Permission denied” when you run it. This just means that you’re running on Unix and have not yet set the execute permission for your program. You might also get “Command not found” even though you can see the program is there! Relax; this just means you have a typo in the first line of your program (the #! or “shebang” line), and it’s saying it can’t find the program you’ve put there. Perhaps you typed prelinstead of perlagain (or left out the space before the -wflag, which this author just did). While we’re at it, you might also get an error looking like .nrecognized switch: -, which can drive you crazy until you discover that it’s from running a program with DOS-style line terminations on Unix. Remove the ^Ms with a tool like dos2unixor perl -pi.bak-e ’s/cM$//’. The distinction between an error and an exception may have been hitherto glossed over in this book, but at this point we need to make it clear. An error simply means that something went wrong; for instance, a system routine may return a value indicating that it can’t do what you have asked. A good program institutes some error handling at this point and checks the return code (more on this later). But the program is still running. An exception occurs (is “thrown,” in the lingo) when some code declares that something intolerable has happened and Perl is simply not going to allow your program to continue running unless you specifically know how to handle (or “catch”) the exception. At this point, your program could be in the middle of some arbitrarily deep nesting of subroutine calls and {}blocks. It ceases executing wherever it is, and starts to percolate back up this stack looking at each level for anything declared that could catch this exception. If it gets all the way to the top without finding such a handler, it executes a default exception handler, which in Perl’s case means printing a message with dieand exiting. Run-time exceptions from Perl may be built in, caused by usestrict, or generated by you. The -wflag can cause a run-time warning message to be displayed, but your program will continue executing. If you’ve followed good coding practices, you should be worried about this possibility, since it may indicate that Perl is working with bad data (data that should be defined but isn’t). If you want to make sure Perl halts when such a warning is generated, you can put this pseudo signal handler near the beginning of your program:[2] [2] This is one of the few times where the difference between warn and print STDERRbecomes apparent; the former is trapped by this sort-of signal handler, the latter is not. local $SIG{__WARN__} = sub { die $_[0] } and Perl exits after printing the warning. 9.1 Symbolic References Now that you’re putting use strictin all of your programs, let’s look at the class of runtime exceptions it can generate. One instance is from the use of symbolic references.
Note: If you are looking for good and quality webspace to host and run your java application check Actions java hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
At least we don’t have to look far to find the problem; the string ended prematurely one character before $quote. There is, of course, more than one way to fix it. We could escape the ” inside the string with backslashes, or we could use the spiffy qq operator, which allows us to pick any delimiter to use for a double-quoted string: while (my ($author, $quote) = each %quotation) { print qq(Quote of the Day: “$quote” by $authorn); } 8.2.2 A Capital Typo Our next horror feature is The Program That Wouldn’t Die: #!/usr/bin/perl use Getopt::Std; sub usage { print “Allowable options: -a, -c, -e, -n count, -un”; Exit; } usage() unless getopts(’acen:u’); print “Starting program $0n”; Let’s run it: % typo.pl -q Unknown option: q Allowable options: -a, -c, -e, -n count, -u Starting program typo.pl Why did this program keep going even after it went into the usage error routine? For the answer, this is the last time we’re going to tell you: Put use strictand -w in all your programs! Because when we do, we see: Bareword “Exit” not allowed while “strict subs” in use at typo.pl line 8. Execution of typo.pl aborted due to compilation errors.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
At this point, we’re going to go on a tour of typo examples with different diagnoses. 8.2.1 Quotable Quotes Our first program sets up a hash %quotation indexed by author and then goes on: while (my ($author, $quote) = each %quotation) { print ‘Quote of the Day: “$quote” by $authorn’; } This runs, but takes us too literally: Quote of the Day: “$quote” by $authornQuote of the Day: “$quote” by $authornQuote of the Day: “$quote” by $authorn… Aha! Nothing is being interpolated because we’re using single quotes. We change them to double quotes: 3 while (my ($author, $quote) = each %quotation) 4 { 5 print “Quote of the Day: “$quote” by $authorn”; 6 } Yikes, now we get three errors: Scalar found where operator expected at typo.pl line 4, near “”Quote of the Day: “$quote” (Missing operator before $quote?) syntax error at typo.pl line 4, near “”Quote of the Day: “$quote” String found where operator expected at typo.pl line 4, near “$quote” by $authorn”" (Missing operator before ” by $authorn”?) Execution of typo.pl aborted due to compilation errors. Once again, we consider only the first message. Whenever Perl provides a hint after the error, read it carefully. Perl suggests that we omitted an operator before $quote, but why would it expect an operator in the middle of a string? Aha we must not be in a string any more. At this point I would have pointed out that the syntax coloring feature of Emacs cperl mode would have shown this, but I promised Ed not to make fractious text editor advertisements.
Note: If you are looking for cheapest and affordable webspace to host and run your servlet application check Astra servlet hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
line 2) (Do you need to predeclare print?) syntax error at typo.pl line 3, near “print “$message ” Global symbol “message” requires explicit package name at typo.pl line 3. Backslash found where operator expected at typo.pl line 3, near “$message ” (Missing operator before ?) Bareword “n” not allowed while “strict subs” in use at typo.pl line 3. String found where operator expected at typo.pl line 3, at end of line (Missing semicolon on previous line?) Can’t find string terminator ‘”‘ anywhere before EOF at typo.pl line 3. Seven error messages from one typo! Let’s concentrate on the first error and ignore the rest for now. The first error complains about a scalar on line 3 instead of a typo. Luckily, we get a hint about the error: Might be a runaway multi-line “” string starting on line 2 This suggests paying special attention to the use of quote marks on line 2, where we find the string delimited by a double quote (”) and a single quote (’). String delimiters must match at the beginning and end. Since there are no interpolated variables or digraphs in this string, either kind of quote will work, as long as we use the same one at each end of the string. Handle only the first warning or error message output by Perl; don’t bother reading the others, just recompile. Error messages after the first one may be a cascade effect and therefore may be eliminated by removing the cause of the first message. It’s usually not worth the time to analyze each message to determine whether this is the case. 8.1.5 Transposition Regular expressions provide a fertile breeding ground for typos. Suppose you want to match and save the last string of letters preceded by white space on a line: /s([a-z])+$/i Looks right, eh? Try it on an example, though: while () { print “Match = $1n” if /s([a-z])+$/i; } __END__ The boy stood on the burning duck
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
What comes out but Match = k Oops. We wanted the last word, not the last letter. Here’s an approach to debugging this problem: We printed $1, which is the text saved between parentheses. We can ignore whatever else the regex contains and focus on what’s between the parens, i.e., [a-z], which we immediately recognize as a character class that hasn’t been qualified with a quantifier. Therefore it can represent only one character, which is what we got. (When saving parentheses match more than once in a regex because of a quantifier, only the last match gets saved. One might wish for a switch that would return all the matches in a list.) As with most typos, identifying it is 90% of the goal. The fix is easy to predict: /s([az]+)$/ i. Here’s a higher-level sort of transposition. Can you tell what it is before reading the explanation? #!/usr/bin/perl -w use strict; my $fmt = “%10s “x5; printf “$fmtn”, qw(Kelvin Celsius Rankine Fahrenheit Reaumur); $fmt = “%10.2f “x5; for (my $kelvin = 0; $kelvin += 10; $kelvin < 500) { my $celsius = $kelvin - 273.15; my $rankine = $kelvin * 9 / 5; my $fahrenheit = $rankine - 459.67; my $reaumur = $celsius * 4 / 5; printf "$fmtn",$kelvin,$celsius,$rankine,$fahrenheit, $reaumur; } Run this, and it does not terminate! You will be calculating temperatures beyond those experienced in the Big Bang. But the very first line of output is Useless use of numeric lt (<) in void context at temp.pl line 13. Weird. Line 13 is the printf statement, and it has no <. According to Perl of Wisdom #24, we should start scanning backwards until we find one. There it is at the beginning of the for statement: forgivably, we transposed the test and iterative clauses. If you'd like to know why Perl fingered line 13 and not line 7 (the for statement), you'll find an explanation in Chapter 10. 8.2 A Menagerie of Typos
Note: If you are looking for top 10 and very good webhost to host and run your jsp application check Actions jsp hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
Consider a program with one extraneous character: use strict; my $x = 1; my $y = 2; $x == $y; print “$x,$yn”; Run the program and Perl prints: 1,2. No errors or warnings are given; this is expected, since each program statement is valid Perl. Now consider a program that differs from the previous one by one character: use strict; my $x = 1; my $y = 2; $x = $y; print “$x,$yn”; When run, Perl prints: 2,2. Output from the second program shows the value of $xset to the value of $y, whereas the first performs no such operation. What did the first program do? In line 4, $x=$y was intended, but $x==$y was coded. The former is an assignment to modify $x, the latter a Boolean test that modifies neither $xnor $y a particularly nasty problem as both commands are correct Perl syntax, and both execute without a complaint, with or without use strict. All this is very elementary, of course, until you wonder “What if I use -w?” Run our first program with -w and Perl returns: Useless use of numeric eq in a void context. File ‘typo1.pl’; Line 4. This reveals yet another reason to use -w in every program: with it, Perl can warn us that while our mistake resulted in syntactically valid Perl, it was odd Perl. It can’t raise a red flag stating “An extra = on line 4!” but it can point out that we’ve executed an essentially useless operation. 8.1.4 Alteration Let’s examine another single typo program: use strict; $message = “Hello World’; print “$messagen”; exit; On running, Perl returns the following: Scalar found where operator expected at typo.pl line 3, at end of line (Might be a runaway multi-line “” string starting on
Note: If you are looking for good and high quality web space to host and run your java application check Vision java hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
use strict $message = “Hello World”; print “$messagen”; exit; On running, Perl returns: HelloWorld. Surprise! The typo prevents strictness from becoming enabled. The absence of the mykeyword allows the assignment to succeed. (Since it’s global, the fact that the assignment happens in an invisible BEGINblock doesn’t matter.) This is one of the most insidious errors conceivable: a single character mistake that causes no warning and no error yet prevents the very error checking the programmer was trying to enable. 8.1.2 A Puzzle Here’s another example of deletion. Can you figure out what’s wrong? use strict; sub foo { my $sref = shift; foreach my $d (@) { find ($sref, $d); } } sub find { } The result: Global symbol “$d” requires explicit package name at typo.pl line 6. syntax error at typo.pl line 7, near “}” syntax error at typo.pl line 8, near “}” Execution of typo.pl aborted due to compilation errors. foreach my $d (@)should instead be foreach my $d (@_). Well, @) is a valid variable in Perl a strange variable to be sure, and not the kind of thing you want to be using intentionally but a variable nevertheless. This robbed the foreach list of its closing parenthesis and caused a wonderful cascade of nonsense. 8.1.3 Insertion Insertion typos probably occur as often as deletion typos, though with different pathologies. An additional character in a variable name is flagged by Perl (if you used -w),and a misspelled command generates a run-time exception. An insertion typo becomes dangerous when the typo is still a valid Perl statement but executes an unexpected function.
Note: If you are looking for good and high quality web space to host and run your java application check Vision java hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
written by people obsessed with minimizing typing: we recommend that you insert a semicolon after every statement, even at the end of a block, since you never know when you might come back later and insert another statement after it.) $message = “Hello World”; print “$messagen” exit; Perl responds with syntax error at line 3, next token “exit” The Perl compiler, like every other compiler we know, often goes somewhat further in your program than the actual error before reporting a problem. Since we’ve never met a compiler that indicated an error for a line number preceding the first one containing an error, we can use Perl’s report of the line number as an upper bound and work backwards from it. The actual syntax error in your program could occur not just on the line reported by Perl, but on any line preceding it. In this case, the line it reported was the last line of the file anyway (which often happens), but them’s the breaks. The strategy for fixing this problem: “syntax error” tells you that Perl has determined the problem to be a straightforward typo (count your blessings), so you know what you’re looking for something that doesn’t look like valid Perl, on or before line 3. Perl gives us an additional piece of information, that the next token is exit. If we’re lucky, that means that the error occurred immediately before that word, so that’s where we start looking. Immediately, we notice a missing semicolon on line 2. Success! Problem located and identified. Case closed. (No, there’s no substitute for looking over the code with a Mark I eyeball. However, if you have reams of code to search, you can reduce the amount you have to check by removing or commenting out parts of it selectively until you see the error message change.) Now let’s consider another missing semicolon that’s far more insidious: use strict my $message = “Hello Worldn”; print $message; exit; This program compiles fine; it even runs without error. Unfortunately, it also runs without output. What happened to the contents of $message? A long or a short way can be used to debug this problem. Let’s try the long way first (the reason for this choice will become apparent in due course). We’ll fire up the debugger (see Chapter 7). The first (meaningful) output from the debugger is
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •