Perl Learning - 8 (IO, <>, print(), @ARGV)

Perl Learning - 8 (IO, <>, print(), @ARGV),第1张

概述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> 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 总结

以上是内存溢出为你收集整理的Perl Learning - 8 (I/O, <>, print(), @ARGV)全部内容,希望文章能够帮你解决Perl Learning - 8 (I/O, <>, print(), @ARGV)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1293068.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存