加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:02:41 所属栏目:大数据 来源:网络整理
导读: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 en
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读