2012-04-30 34 views
0

可能重複:
Easiest way to open a text file and read it into an array with Perl在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 

回答

6

如果你是要發出聲音文件,請使用File::Slurp

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

首先,你不能調用數組$1在Perl,因爲這(和所有其他標量與一個數字作爲其名稱)用於由正則表達式引擎,所以只要運行正則表達式匹配就可以被覆蓋。其次,你可以比這更容易地將文件讀入數組中:只要在列表上下文中使用菱形運算符。

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

然後,您可以獲取該文件的線的陣列,由當前行分隔符默認情況下是你可能會想到它是即平臺的換行符是什麼分裂。

第三,你的pushf2a子很奇怪,特別是傳入一個數組然後不使用它。你可以寫一個子程序這需要一個文件名,並返回一個數組,從而避免與內部您的問題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); 

總的來說,我不能確定最好的解決辦法是什麼,因爲我不能完全使正是你想要做的,但也許這會幫助你。

0

不明白,你要像$1數組什麼,但良好的做法是這樣的代碼:

我包含文件以及它們的家鄉地址的內容 - 陣列的哈希

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; 
+0

而是打開和關閉詞法文件句柄,只需用'打開我的$ tmp_fh,...'聲明它的循環中。它在超出範圍時會自動關閉(在循環迭代結束時)。 – TLP

+0

謝謝:)改變:) – gaussblurinc