【问题标题】:How to store different lines of text file in different array elements in perl [closed]如何在perl中的不同数组元素中存储不同行的文本文件[关闭]
【发布时间】:2012-11-07 02:25:29
【问题描述】:

perl中如何将不同行的文本文件存储在不同的数组元素中

例如 文本文件包含

US
London

如何将 US 存储在数组 [0] 中,将 London 存储在数组 [1] 中

【问题讨论】:

  • 请明确问题
  • 只需在空间上分割你的行。或者你想要别的东西?
  • @Rohit Jain:它们之间有一个换行符,现在格式更好
  • @ysth - 谢谢。现在读起来确实更好。
  • 这并不复杂。 Try something.努力吧。

标签: arrays perl file-io


【解决方案1】:

这是一种选择:

use strict;
use warnings;

my $fileName = 'text.txt';

open my $fh, '<', $fileName or die $!;
chomp( my @array = <$fh> );
close $fh;

print qq{\$array[0] contains "$array[0]"\n};
print qq{\$array[1] contains "$array[1]"};

输出:

$array[0] contains "US"
$array[1] contains "London"

【讨论】:

    【解决方案2】:

    这将打开一个文件并将每一行读入一个数组:

    open my $fh, '<', $filename;
    chomp(my @lines = <$fh>);
    close $fh;
    

    请参阅perlfaq 了解更多信息。

    【讨论】:

    • chomp(@lines) 删除换行符。
    • @ysth,谢谢,我总是忘记咀嚼 :)
    【解决方案3】:
    @arr=();
    open(KJ,"ur_file");
    @arr=<KJ>;
    close(KJ);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多