perl的檔案操作 1

2021-09-06 03:22:14 字數 1599 閱讀 1255

假如有乙個從web上拷貝下來的檔案

01 #!/usr/bin/perl -w 

02   

03 use tk; 

04   

05 $tk::strictmotif = 1; 

06   

07 $main = mainwindow->new(); 

08   

09 $button1 = $main->button(-text => "exit", 

10                          -command => \&exit_button, 

11                          -foreground => "orangered" ); 

12   

13 $button1->pack(); 

14 $button1->configure(-background => "white" ); 

15 $button2 = $main->button(-text => "push me", 

16                          -command => \&change_color, 

17                          -foreground => "black",  

18                          -background => "steelblue"); 

19   

20 $button2->pack(); 

21   

22 mainloop(); 

23   

24 sub exit_button  

28   

29 sub change_color

現在想去掉其中的前導數字和空格,可用以下**解決(列印在螢幕上)

use strict;

use warnings;

my $file="./s1";

if (! open (file,"$file"))

while ()

}當然可以直接修改檔案,將修改的結果直接存回原檔案,即修改原檔案,可以用open檔案操作,如下:

use strict;

use warnings;

my $tmp;

my $file="./s1";

my $buffer="./tmp.txt";

open f,"$file" or die $!;

open t,">>$buffer" or die $!;

$^i=".bak";   #空時,則不備份

while ($_=readline f) }}

print $tmp;

print t $tmp;

close t;

close f;

rename ("$buffer","$file") or die ("file in use!");

用sed更簡潔

sed -i 's/^[0-9]*[ ]*//' s2.txt

sed '/^[[:space:]]*$/d' s2.txt     #刪除全部空行

perl 檔案操作

perl中檔案操 基礎在perl中,提供了三種檔案控制代碼 stdin,stdout,stderr.它們可以由父程序建立的檔案或者裝置會自動開啟.一般使用open函式來建立檔案控制代碼.open函式的語法是唯讀模式時為 open filehandle,somename 其中filehandle是檔案...

perl 檔案操作

1 讀取某檔案,如果該檔案不存在,則報錯,並提示出錯原因 open db,home ellie myfile or die can t open file n 2 讀寫檔案的方法 open fh,opens filename for reading.讀 the symbol is optional....

Perl的檔案操作(1)(適合初學者)

讀入單個記錄 有乙個容易的方法讀入filehandles 用 操作符。在標量內容下,它返回檔案中的下乙個記錄,或者返回未定義出錯資訊。我們可以使用它來把一行讀入到乙個變數中 line die unexpected end of file unless defined line 在迴圈語句中,我們可以...