简体   繁体   English

如何使用Perl将行读入数组

[英]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 但我建议进行一些改进

  1. Always use 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. 它有助于检测很多可能的问题。
  2. Code has no error handling. 代码没有错误处理。
  3. Use variables for file handlers. 将变量用于文件处理程序。 Using bareword is deprecated. 不建议使用bareword
  4. Open file for read if you need to only read from a file. 如果您只需要读取文件,则打开文件进行读取。
  5. Maybe the ending newlines would be removed form the array. 也许结尾的换行符将从数组中删除。
  6. If the file not needed to be kept opened it worth to close it. 如果不需要保留该文件,则值得将其关闭。 Here is not needed as exit will automatically close it implicitly, but it is a good practice to close the files explicitly. 不需要此处,因为exit会自动隐式关闭它,但是,最好是显式关闭文件。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM