2012-01-23 42 views

回答

8

很簡單(這是假設,當然,你的陣列被明確指定爲一個數組,你的問題完全不是那麼回事明確):

#!/usr/bin/perl -w 
use strict; 

my @a = (1, 2, 3); # The array we want to save 

# Open a file named "output.txt"; die if there's an error 
open my $fh, '>', "output.txt" or die "Cannot open output.txt: $!"; 

# Loop over the array 
foreach (@a) 
{ 
    print $fh "$_\n"; # Print each entry in our array to the file 
} 
close $fh; # Not necessary, but nice to do 

以上腳本將寫入以下爲 「output.txt的」:

1 
2 
3 
+4

現在你應該用 '開放' 的3個參數的形式。另外你最好把你的文件句柄放到一個詞法中,例如「打開我的$文件,'>','output.txt'...」 – zgpmax

+0

@ hochgurgler +1原因可以在這裏找到:http://stackoverflow.com/questions/1479741/why-is-three-argument打開電話與詞法文件句柄一個perl最佳做法 – dgw

+0

@ hochgurgler感謝您的信息。我不知道存在三個參數的形式,因此這是一個最佳實踐! –

4

如果你不想foreach循環,你可以這樣做:

print $fh join ("\n", @a); 
+3

您的「地圖」是多餘的。 – Sobrique

+0

@Sobrique:確實,因爲'加入'內建已經是'loopy'了。我已將其刪除,並將圓括號加入參數的參數中(待審覈)。 –