2011-09-27 65 views
-2

我想創建一個範圍從1..10000000,包含「一些文本」的指定數量的文件,你如何在Perl中做到這一點?如何用perl創建x個文件?

在此先感謝!

+0

那麼,是什麼阻止你?打開相關的文件句柄並寫入。 – 2011-09-27 16:59:41

+0

如果你在做家庭作業時遇到問題,至少告訴我們你試過的是什麼,而不是讓我們去做。 – HerbN

回答

0

試試這個:

my $count = 3; 
for (my $i = 0; $i < $count; $i++) { 
    open(my $f, ">>file$i.txt") or die("couldn't open file$i.txt"); 
    print $f "some text"; 
    close($f); 
} 
+0

謝謝!這就是我一直在尋找的! – user967536

+5

如何使用Perl? 'foreach my $ i(1.. $ count){open(my $ fh,'>',「file $ i.txt」)或死「不能創建文件$ i.txt:$!」;打印{$ fh}「一些文字」;關閉$ fh; } – mirod

+2

讓我們不要混淆他 –

3

您的工作方式與您在其他任何語言中使用相同。分解任務成一系列小步驟,你可以實現:

  • 環路周圍:
  • 打開一個文件,並寫入文本。

所以,你可能有這樣的代碼:

my $count = 0; 
while($count < 10000) 
{ 
    open(my $fh, '>', "output.$count") 
     or die "Failed to open file: $!"; 
    print $fh "sometext\n"; 
    close($fh); 

    $count += 1; 
} 
+0

感謝您的快速響應! – user967536

+2

你實際上可以使用'foreach my $ i(1..100000){...'這裏,perl負責不爲你預先分配列表。 – mirod

0

雖然你可以創建一個目錄千萬的文件,這是不可取的,因爲四處尋找該目錄會證明麻煩。 ls不會返回幾個小時,bash自動完成的文件名將會掛起,並且通常您需要終止終端以再次使用它。

考慮跨多個目錄分區文件。您可以使用md5,sha1,模數(s),文件名中的n位數組等來實現分區。將任何目錄中的文件總數保持在少於幾千個是可取的。

下面是一個例子使用MD5:

use File::Path qw(make_path); 
use Digest::MD5 qw(md5_hex); 

use constant DIRECTORY_ROOT => '/path/where/you/want/these/files'; 
use constant FILE_SEP  => '/'; 
use constant MAX_FILES  => 10; 

for my $count (1 .. MAX_FILES) { 
    my $subdir = substr(md5_hex($count), 0, 2); # First 2 characters 

    my $dir = join FILE_SEP, DIRECTORY_ROOT, $subdir; 
    make_path($dir); 
    my $file = join FILE_SEP, $dir, $count; 

    open(my $fh, '>', $file) 
     or die "Failed to open file $file : $!"; 
    print $fh "some text\n"; 
    close($fh); 
} 

這將創建下列文件集:

./c9 
./c9/8 
./16 
./16/6 
./ec 
./ec/3 
./c8 
./c8/2 
./e4 
./e4/5 
./a8 
./a8/4 
./d3 
./d3/10 
./8f 
./8f/7 
./45 
./45/9 
./c4 
./c4/1