[英]How to read a line into an array using perl
I am using perl for the first time. 我是第一次使用perl。 I am trying to read a line from input file and store it in an array. 我正在尝试从输入文件中读取一行并将其存储在数组中。 Note that the the input file contains a single line with a bunch of words. 请注意,输入文件包含一行带有单词的一行。
I tried using the following code: 我尝试使用以下代码:
open input, "query";
my @context = <input>;
But this gives a syntax error. 但这会带来语法错误。 How could i fix this? 我该如何解决?
It doesn't give a syntax error. 它没有给出语法错误。 IT even works fine if there's only one line. 如果只有一条线路,IT甚至可以正常工作。 The following will only get the first line even if there are more than one: 即使有多个行,以下内容也只会获得第一行:
my @context = scalar( <input> );
But why wouldn't you just do 但是你为什么不做
my $context = <input>;
What is the syntax error? 语法错误是什么? IMHO it writes none. 恕我直言,它不会写入任何内容。 But I would suggest some improvements 但我建议进行一些改进
use strict; use warnings;
始终使用use strict; use warnings;
use strict; use warnings;
as a first line! 作为第一线! It helps to detect a lot of possible problems. 它有助于检测很多可能的问题。 bareword
is deprecated. 不建议使用bareword
。 So it could be: 因此可能是:
#!/usr/bin/perl
use strict;
use warnings;
open my $input, "<infile" or die "$!";
my @context = map { chomp; $_;} <$input>;
close $input;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.