Monday, February 18, 2008

Learning Perl, 4th Edition Notes 0x4

Learning Perl, 4th Edition Notes 0x4 by DaNmarner * If <STDIN> encounters an end-of-file, it returns undef, which is handy when it is used as a while condition:
while (<STDIN>) { print; }
* while reads a line and start an iteration each time. In contrast, foreach dosen't start the loop until it read the whole thing. * The diamond operator (<>) reads in the files listed in invocation arguments, and returns a list. * The invocation arguments are automatically stored in the array @ARGV. * When printing an interpolated array, there will be spaces between each elements. * A C-like printf is available in perl, which requires a format string and a list of things to print. * A trick to print arrays with printf:
$format_string = "something first".("%s " x @the_array_to_be_printed); printf $format_string, @the_array_to_be_printed;
* A filehandle is the name in a Perl program for an I/O connection between Perl process and the outside world. * A Perl process automatically inherits, at least, three filehandles from its parent process when starts: STDIN, STDOUT, STDERR. * To open a filehandle, use open, followed by the filehandle name and a double quoted file name:
open NAME, "file_name";
The file name can be leaded by ">", "<" or ">>", which stands for overwrite, read from or add to a file. Another way to do this it to use three arguements:
open NAME,">>",$file_name;
* open will return a false value if it opens a "bad" filehandle. * To close a filehand, use close to lead the filehandle name. * die accepts a string to print out into STDERR before it ends the process. It also stores the error message given by the system into $!; * worn works in the same way as die, but it dosen't quit the program. * A filehandle name following print or printf will change the latters desination. * select changes the default output filehandle:
select FILEHAND;
* If a filehandle is reopened, the original one will be hang up, and will return when the new one terminates.

2 comments:

Randal L. Schwartz said...

'open NAME "file_name";' - missing a comma after NAME. It's not like print with a handle, which does not include the comma.

DaNmarner said...

Thank U !