perl is immortal ultimate scripting language. make sure to read all our posts.
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
• Login • skip to content
perl is immortal ultimate scripting language. make sure to read all our posts.
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
You’re not required to stick to only one idiom, mind you. It’s common for people to choose different ones according to the way they think about the operation they’re expressing. You have to be fanatical about checking return codes if you want to write quality programs. For instance, in the first example in the preceding list, the copyfunction from File::Copyalso returns true or false and sets $! on failure. It would be a strange sort of program that wouldn’t have a reason to ensure that this had happened. Some functions return something besides true/false but still set $!, for example, chmod, chown, and unlinkeach take a list of files to operate upon, return the number of files actually modified, and if there were any errors, set $! to the last one. (Unfortunately it’s not possible to tell which file(s) had problems without checking manually afterwards.) Know your operating system. A student in one of my classes encountered the following. The assignment was to create a temporary directory and a bunch of files in it, perform some operations on them, and then to remove the files and the directory. Part of his code looked something like this: foreach my $file (@files) { open OUT,”>$file” or die “Can’t open $file: $!n”; # write something to the file } # Open the files in the directory and do something # with the contents die “Unlink didn’t get everything: $!n” unless unlink @files == @files; chdir ‘..’ or die “Couldn’t go up a level: $!n”; rmdir $tmpdir or die “Couldn’t rmdir $tmpdir: $!n”; Every return code dutifully checked, but the rmdir failed, and $! said, “Directory not empty.” Yet when he looked in the directory, there were no files there. What was going wrong? The problem was that he had omitted the close statement from the loop that created the files. Whenever Perl encounters an open statement using an existing filehandle, it closes that filehandle for you, so all but the last file had already been closed. On Unix, if any process has a file open, it is not removed by unlink until the file is closed, so the last file in @files had not been removed at the time the rmdir was executed. But then the program exited, which meant that all its open filehandles were closed; at that point the file was removed, destroying the evidence.
Hint: This post is supported by Gama hrvatski web hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
15 $cases_sold->{$type} += $sold; 16 } 17 else 18 { 19 warn “I don’t know the food type $foodn”; 20 } 21 } 23 foreach my $type (keys %$cases_bought) 24 { 25 print $cases_bought->{$type} - $cases_sold->{$type}, 26 ” cases of $type on handn”; 27 } We used a function new to Perl 5.6.0, fields::phash, which takes the sting out of creating pseudo-hashes, and at the same time avoids the repetition we had on the first two lines of our previous version. If pseudo-hashes are retained in later versions of Perl but their implementation alters, fields::phash will be changed to hide that implementation change from you. When we want to iterate over the different food types to print our report, we just use the keys of a pseudo-hash (which means we no longer get to pick the order, unless we sort the keys). 9.2 Check That Return Code! The Perl built-in functions that might fail return a special value to alert you that they have done so. Usually, this value is false. (Functions that call out to the operating system to do their work will put the type of error in the $!variable.) This allows a number of common colloquialisms for checking and handling it, the most famous of which is the open-or-dieidiom: open DICT, ‘/usr/dict/words’ or die “I’m at a loss for words: $!”; This being Perl, there are many other ways of expressing the same thing. Pick one that works for you: if (mkdir $tmpdir, 0755) { copy $dbfile, “$tmpdir/$dbfile.$$” } else { die “Couldn’t create $tmpdir because $!”; } die “Can’t chdir to $subdir: $!” unless chdir $subdir; print chmod (0644, @files) ? “Success!” : “Failure: $!”;
Hint: This post is supported by Gama hrvatski web hosting services
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
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
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
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
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
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
Posted by mario at 10:32 AM. Filed under: perl
No Comments • Trackback • Permalink •
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 •