#Example21 #对文件的处理
#!/usr/bin/perl -w
#Usage:perl test1.pl test?.txt #用"?"不用"*"可以加快程序运行
use strict;
chomp(my $date = `date`); #引用系统命令date,取当前系统日期,保存到"$date"中
$^I = ".bak"; #程序自动生成备份文件,并将".bak"追加到名字后面去
while (<>){ #读入txt文件
s/^print/printf/;
s/#.*
//;
print;
}
#perl -p -i.bak -w -e 's/print/printf/g' test*.pl.bak
#这是一条命令
#-p自动生成一小段程序 -i.bak 制定后缀名(如果不需要备份,只写-i即可) -w打开警告信息 -e后面跟着的是程序代码
#将test*.pl.bak文件中所有的print改成printf,并生成源文件的备份,将.bak追加到备份文件后面
#于是,我们得到的文件时test*.pl.bak和test*.pl.bak.bak
#Example21 #Perl程序控制
#!/usr/bin/perl -w
if ($freed =~ /^[A-Z_]w*$/i){
print "The value of $freed really look like a Perl identifier name.
";
} else {
print "The value of $freed doesn't look like a Perl identifier name.
";
}
#以上程序与下面的功能完全一样
unless($freed =~ /^[A-Z_]w*$/i){
print "The value of $freed doesn't look like a Perl identifier name.
";
} else {
print "The value of $freed really look like a Perl identifier name.
";
}
while($j < $i){
$j*=2;
}
#以上程序与下面的功能完全一样
until($j > $i){
$j*=2;
}
print "The value of $freed really look like a Perl identifier name.
" if $freed =~ /^[A-Z_]w*$/i ;
#以上程序与下面的功能完全一样
if ($freed =~ /^[A-Z_]w*$/i){
print "The value of $freed really look like a Perl identifier name.
";
}
#开开眼界吧,这都什么东西啊,但是他们确实可以执行
&error("Invalid input") unless &valid($input);
$i *= 2 until $i > $j;
print " ", ($n +=2) while $n < 10;
&greet($_) foreach @person;
#Example22 #定义多个变量
#!/usr/bin/perl
$_ = "Hello there, neigthor!"; #一下子定义三个变量
my($f, $s, $t) = /(S+) (S+), (S+)/;
printf "First: $f
";
printf "Second: $s
";
printf "Third: $t
";
$x = join ":","$f","$s","$t"; #再连接起来
print "$x
";
#Example23 #读入文件,并做统计
#!/usr/bin/perl
while (<>) { #转世操作符,分行读入
foreach (split) { #用空格拆分
$total++;
next if /W/; #如果该字符串含有特殊字符,跳过下面的
$valid++; #不含特殊字符的正常的单词
$count{$_}++; #统计每个单词个数
}
}
print "Total things = $total, Valid words = $valid!
"; #输出统计信息
foreach $word (sort keys %count) { #这个很好玩,再猜几次吧
print "$word was seen $count{$word} times.
";
}
#Example24 #统计字符串是否曾经出现过
#!/usr/bin/perl -w
my @people = qw{ Fred abc Fred bam bam nm bc nu ;lll};
my %seen;
for (@people) {
print "I've seen you somewhere before,$_!
"
if $seen{$_}++;
}
#Example25 #获取某类文件,并存入@ARGV中
#!/usr/bin/perl -w
#第一段的执行方式是: perl test5.pl *.pl
#第二段的执行方式是: perl test5.pl
#foreach $arg (@ARGV) {
# print "One arg is $arg
";
#}
#my @ARGV = glob "*.pl";
#my @ARGV = <*>;
my $dir = "/bocnet/app_bak/yu/yu_perl";
my @ARGV = <$dir/* $dir/.*>;
foreach $arg (@ARGV) {
print "One arg is $arg
";
}
#Example26 #目录句柄
#!/usr/bin/perl -w
my $dir = "/bocnet/app_bak/yu/yu_perl";
opendir DH,$dir or die "Cannot open $dir: $!";
foreach $file (readdir DH) {
print "One file in $dir if $file
";
}
closedir DH;