|
Print Output Print takes a series of things to print separated by commas. By default, print writes to the STDOUT file handle.
print "Woo Hoo\n"; ## print a string to STDOUT $num = 42; $str = " Hoo"; print "Woo", $a, " bbb $num", "\n"; ## print several things
An optional first argument to print can specify the destination file handle. There is no comma after the file handle, but I always forget to omit it.
print FILE "Here", " there", " everywhere!", "\n"; ## no comma after FILE
File Processing Example
As an example, here's some code that opens each of the files listed in the @ARGV array, and reads in and prints out their contents to standard output...
#!/usr/bin/perl -w require 5.004; ## Open each command line file and print its contents to standard out foreach $fname (@ARGV) { open(FILE, $fname) || die("Could not open $fname\n"); while($line = ) { print $line; } close(FILE); }
The above uses "die" to abort the program if one of the files cannot be opened. We could use a more flexible strategy where we print an error message for that file but continue to try to process the other files. Alternately we could use the function call exit(-1) to exit the program with an error code. Also, the following shift pattern is a common alternative way to iterate through an array...
while($fname = shift(@ARGV)) {...
|