![]() |
![]() |
![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() |
![]() |
![]() |
To access the contents, click the chapter and section titles.
Perl CGl Programming: No experience required.
Input, OutputThe next two lines in access.pl are liable to be a little confusing to beginners. close (COUNT); open (COUNT, ">$CountFile"); Why do we close the file and then instantly re-open it? And why is $CountFile in quotes this time with a > character in front of it? The > operator is the difference between input and output on a file in Perl. You might remember the > and < symbols as the operators for redirection of input and output in MS-DOS. These conventions actually were borrowed from UNIX, so its no wonder theyre used in Perl. When you put the greater-than sign in front of the file name parameter to open, the file is opened for output, or writing, and it will create the file, if it doesnt exist, or overwrite anything that is in the file. The less-than sign opens the file for input to the program, or reading, but this is so common that Perl regards it as the default if you leave it off. The append symbol (>>) will append anything you write to the file to what already is in the file. You put quotes around the file name variable $CountFile to avoid confusing the Perl interpreter between the output redirection symbol and the $ to indicate a scalar variable.
So, the code snippet close (COUNT); open (COUNT, >$CountFile); creates counter.dat the first time you run the program, and opens it for overwriting on any subsequent runs.
print Works with Files, TooThe last bit of code from access.pl brings up a couple of interesting new Perl concepts. $Counter += 1; print COUNT $Counter; print "$CountFile has been written to $Counter times.\n"; close (COUNT); In the first line, $Counter += 1, the += is a shortcut borrowed from the C programming language. In this example, it is identical to writing: $Counter = $Counter + 1; Why not simply write $Counter = $Counter + 1? Well, for one thing $Counter += 1 is shorter and therefore follows the twin precepts of laziness and impatience. However, some programmers might insist that the longer form is clearer, that is, that it more clearly states the intention of the code. In the end, its a matter of taste.
The other line worthy of special mention in this code snippet is the second: print COUNT $Counter; This brings up a feature of print that we havent covered yet: The function presumes that its first argument is a file handle. If its left out, print will use the current output file handle, which, unless you have done something special and specific, will be the standard output, or the screen.
|
![]() |
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. |