InPut and Output
 
can get user's input, in scalar context it returns the next line.
 
$line=;
chomp($line);
chomp($line=) # same as above two lines
 
while(defined($line=)){
 print "I saw $line";
 }
 
When the input ends(CTRL+D) with undef, the while loop will ends too.
 
while(){
 print "I saw $_";
 }
 
Only in while or for(contidtion), the returns its line to $_, if there's something else in condition, it doesn't work.
In fact has nothing to do with $_
 
foreach(){     # list context
 print "I saw $_";
 }
 
while() is scalar context, once it gets one line the line be will be printed. Then gets another line, one line a time.
foreach() is list context, so it will gets all lines at a time, then print one line at a time going through elements.
 
$ ./while_STDIN.pl
line 1
I saw line 1
line 2
I saw line 2
 
$ ./foreach_STDIN.pl
line 1
line 2
line 3
I saw line 1
I saw line 2
I saw line 3
 
Another way is <>, it's called "dismond operator".
 
while(<>){
 chomp;
 print "It was $_ that I saw!\n";
 }
 
<> gets arguments from array @ARGV, like sub &routine gets arguments from array @_

When the program starts to run, the arguments are already in @ARGV, we can modify it before <> comes, then the command line arguments are ignored.
 
If @ARGV is empty, <> gets lines from user input (keyboard); otherwise it gets lines from files of arguments.
 
@ARGV=qw#larry mor curly#; # force to use these 3 files
while(<>){
 chomp;
 print "It was $_ that I saw!\n";
 }
 
Operater 'print' put everything it got to the standard device of output, typically your screen.
If you need sapce or new line you have to put it in 'print'.
 
$name="Larry Wall";
print "Hello there, $name, did you know that 3+4 is", 3+4, "?\n";
my @array=qw/hello there how are you/;
print @array; # no space between elements
print "@array"; # spaces in elements
 
$ ./print_array.pl
hellotherehowareyou
hello there how are you

#!/usr/bin/perl
my @array=("hello
",
"there
",
"how
",
"are
",
"you
");
print @array;
print "\n@array";
$ ./print_array.pl
hello
there
how
are
you
 
hello
 there
 how
 are
 you
 
 If 'print' has () with it, print() is a function, it returns true if succeeds false if fails.
 
print (2+3)*4;  # gets 5
(print (2+3)) * 4; # same as above