【问题标题】:In Perl, how can I read the contents of a file into an array? [duplicate]在 Perl 中,如何将文件的内容读入数组? [复制]
【发布时间】:2012-04-30 10:54:59
【问题描述】:

可能重复:
Easiest way to open a text file and read it into an array with Perl

我是 Perl 的新手,希望每个文件都将文件的内容推送到一个单独的数组中,我通过以下方法设法做到了这一点,它使用 if 语句。但是,我想为我的阵列提供 1 美元之类的东西。那可能吗?

#!/usr/bin/perl

use strict;
my @karray;
my @sarray;
my @testarr = (@sarray,@karray);
my $stemplate = "foo.txt";
my $ktemplate = "bar.txt";
sub pushf2a  {
  open(IN, "<$_[0]") || die;
  while (<IN>) {
    if ($_[0] eq $stemplate) {
      push (@sarray,$_);
    } else {
      push (@karray,$_);
    } 
  }
  close(IN) || die  $!;
}
&pushf2a($stemplate,@sarray);
&pushf2a($ktemplate,@karray);
print sort @sarray;
print sort @karray;

我想要这样的东西:

#!/bin/sh
myfoo=(@s,@k)
barf() {
  pushtoarray $1
}
barf @s
barf @k

【问题讨论】:

    标签: perl


    【解决方案1】:

    如果您要 slurp 文件,请使用 File::Slurp:

    use File::Slurp;
    my @lines = read_file 'filename';
    

    【讨论】:

      【解决方案2】:

      首先,您不能在 Perl 中调用数组 $1,因为它(以及所有其他以数字作为名称的标量)被正则表达式引擎使用,因此在运行正则表达式匹配时会被覆盖.

      其次,您可以比这更容易将文件读入数组:只需在列表上下文中使用菱形运算符。

      open my $file, '<', $filename or die $!;
      my @array = <$file>;
      close $file;
      

      然后你会得到一个文件行的数组,由当前行分隔符分割,默认情况下你可能期望它是你的平台的换行符。

      第三,你的pushf2a sub 很奇怪,尤其是传入一个数组然后不使用它。您可以编写一个接受文件名并返回数组的子例程,从而避免内部 if 语句的问题:

      sub f2a {
          open my $file, '<', $_[0] or die $!;
          <$file>;
          # $file closes here as it goes out of scope
      }
      
      my @sarray = f2a($stemplate);
      my @karray = f2a($ktemplate);
      

      总的来说,我不确定最好的解决方案是什么,因为我无法完全确定您想要做什么,但也许这会对您有所帮助。

      【讨论】:

        【解决方案3】:

        不明白,你想要$1 之类的数组,但好的做法是这段代码:

        我在 HoA 中包含文件及其内容 - 数组哈希

           my $main_file = qq(container.txt);  #contains all names of your files. 
           my $fh;      #filehandler of main file
           open $fh, "<", $main_file or die "something wrong with your main file! check it!\n";
           my %hash;    # this hash for containing all files
        
           while(<$fh>){
                my $tmp_fh;  # will use it for files in main file
                #$_ contain next name of file you want to push into array
                open $tmp_fh, "<", $_ or next; #next? maybe die, don't bother about it
                $hash{$_}=[<$tmp_fh>]; 
                #close $tmp_fh; #it will close automatically
           }
           close $fh;
        

        【讨论】:

        • 不用打开和关闭词法文件句柄,只需在循环中用open my $tmp_fh, ... 声明它。当它超出范围时(在循环迭代结束时)它将自动关闭。
        猜你喜欢
        • 2014-03-15
        • 1970-01-01
        • 1970-01-01
        • 2010-12-25
        • 1970-01-01
        • 2019-09-24
        • 1970-01-01
        • 2013-05-13
        • 1970-01-01
        相关资源
        最近更新 更多