Perl 作为一门文本处理语言,自然会有他的递归写法,小弟这边分享两个例子,希望对大家能有用!
阶乘(最经典的递归)
#!/usr/bin/perl -s my $Result = 1; sub GetResult{ my $num = shift; if( $num != 1 ){ $Result = $Result * $num; print "Result:$Result | num:$num\n"; $num--; GetResult($num); } } GetResult(‘10‘);
运行结果:
[root@virfed64 ~]# ./GetResult.pl Result:10 | num:10 Result:90 | num:9 Result:720 | num:8 Result:5040 | num:7 Result:30240 | num:6 Result:151200 | num:5 Result:604800 | num:4 Result:1814400 | num:3 Result:3628800 | num:2
遍历linux的文件目录找出自己想要的文件
[root@virfed64 ~]# cat Scan.pl #!/usr/bin/perl -s # use Cwd; sub ScanDirectory{ my $workdir = shift; my $startdir = cwd; chdir $workdir or die "Unable to enter dir $workdir:$! \n"; opendir my $DIR,‘.‘ or die "Unable to open $workdir:$! \n"; my @names = readdir $DIR or die "Unable to read $workdir:$!\n"; closedir $DIR; foreach my $name (@names){ next if ($name eq ‘.‘); next if ($name eq ‘..‘); if ( -d $name ){ ScanDirectory($name); next; } if($name eq ‘core‘){ if (defined $r ){ unlink $name or die "Unable to delete $name :$! \n"; } else{ print "Found one in $workdir!\n"; } } } chdir $startdir or die "Unable to change to dir $startdir:$!\n"; } ScanDirectory(‘.‘);
运行结果就是找到文件或者删除
原文地址:http://realsilsa.blog.51cto.com/8240339/1774587