微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Perl Learning - 8 (I/O, <>, print(), @ARGV)

InPut and Output
 
<STDIN> can get user's input,in scalar context it returns the next line.
 
$line=<STDIN>;
chomp($line);
chomp($line=<STDIN>) # same as above two lines
 
while(defined($line=<STDIN>)){
 print "I saw $line";
 }
 
When the input ends(CTRL+D) with undef,the while loop will ends too.
 
while(<STDIN>){
 print "I saw $_";
 }
 
Only in while or for(contidtion),the <STDIN> returns its line to $_,if there's something else in condition,it doesn't work.
In fact <STDIN> has nothing to do with $_
 
foreach(<STDIN>){     # list context
 print "I saw $_";
 }
 
while(<STDIN>) is scalar context,once it gets one line the line be will be printed. Then gets another line,one line a time.
foreach(<STDIN>) 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐