对于如上面一章所写的下载的文件
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,将文件与数组绑定,这样对数组的修改即对应到对文件的修改
#!/usr/bin/perl -w
use Tie::File;
my $file=shift;
my @array;
tie @array,'Tie::File',$file or die "$!\n";
foreach (@array) {
chomp;
s/.{3}//;
if (/(\S+)/) {
if (/\b(sub)/) {
$_="\r\n" . $_ . "\n"
}
else {
$_=$_ . "\n";
}
}
}
用此方法唯一的问题是空行无法删除,望有兴趣的读者可以自己研究完善这个代码!
(
附:完成此功能的sed文件
$ cat w_file.sed
#!/bin/sed -f
s/^.\{3\}//g
/^[[:space:]]*$/d
/^sub/ i
运行:
$ ./w_file.sed s2
简洁明了!!
)