perl的文件操作(2)

来源:互联网 时间:1970-01-01

对于如上面一章所写的下载的文件

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 {

25     print "You pushed the button!/n";

26     exit;

27 }

28  

29 sub change_color {

30     $button1->configure(-background => "red",

31                         -foreground => "white");

32     $button2->configure(-background => "maroon",

33                         -foreground => "white",

34                         -font       => "-*-times-bold-r-normal-20-140-*");

35 }

如果要去掉前导数字和空格,并且sub前保留一个空行可用

use strict;
#use warnings;

my $tmp;
my $file="./s2";
my $buffer="./tmp.txt";
open F,"$file" or die $!;
open T,">>$buffer" or die $!;
$^I=".bak"; #空时,则不备份

while (readline F) {
  if (defined) {
    chomp;
    s/.{3}//;
    if (/(/S+)/) {
       if (//b(sub)/) {
         $tmp=$tmp . "/r/n$_/n"
       }
       else {
         $tmp=$tmp . "$_/n";
       }
    }
  }
}
print $tmp;
print T $tmp;
close T;
close F;
rename ("$buffer","$file") or die ("file in use!");

也可用Tie::File,将文件与数组绑定,这样对数组的修改即对应到对文件的修改


相关阅读:
Top