$line = <STDIN>; #read next line of input from STDIN
while (defined($line = <STDIN>)) {
print $line; #print out all lines until EOF
}
Equivalently...
while (<STDIN>) {
print $_; #Using the default varaible $_
}
@alllines = <STDIN>; #Reads whole file into array...each element is 1 line
The Diamond Operator
Basically, the diamond operator takes as its input a list of files given on the command line. If one of those files is named '-' it uses STDIN as the input for that file. It will go through each file listed. Here's an example...
FILE1
Hey
There
FILE2
North
Carolina
myprogram.pl
while (<>) {print $_;}
Now, when we run ./myprogram FILE1 FILE2, we would see the following on the screen:
Hey
There
North
Carolina
It just took input from the first file and then the second file as its input.
The names of the files are stored in a special array called @ARGV. If you edit this variable before your program gets to the diamond operator, it will alter what the operator uses for input...for example, let's change our program to the following:
shift @ARGV;
while (<>) {print $_;}
Now, when we run ./myprogram FILE1 FILE2, FILE1 gets shifted off, so the only file processed is FILE2.
Standard Output
The difference between interpolating and array and not
@myarray = ("Alan","Bob");
print "@array"; #Prints Alan Bob
print @array; #Prints AlanBob - Not interpolated
Using printf
If you're familiar with printf from C, Perl's is very similar.
In the string you are printing, you put special directives in that tell printf what type of data to print and how to format it:
printf "Hi %s, I'm %d years old\n.", "John", 10.2; #%s means string, %d is decimal integer..chops off decimal
Prints: Hi John, I'm 10 years old.
printf "%g %g %g", 2.5, 3, 51**17; #%g tries to format a number in a 'good' way
Prints: 2.5, 3, 1.0683e+29
Your can also specify widths:
printf "%5d\n", 10; #Put 10 in a field of length 5
Prints: ___10 - The _s are spaces
printf "%2d\n", 100;
Prints: 100
printf "%5s\n", "Hi";
Prints: ___Hi
printf "%-5s\n", "Hi";
Prints: Hi___
printf "%5f\n", 1+2/3; #floating point number...rounds off
Prints: 1.667
printf "%5.2f\n", 1+2/3;
Prints: _1.67
printf "%5.0f\n", 1+2/3;
Prints: ____2
Everything is a string, so you could store the format string in a variable:
@myarray = ("Alan", "Bob");
$format = "Those present are: " . ("%s " x @myarray) . "\n";
printf $format, @myarray;
Prints: Those present are: Alan Bob