標籤:目錄 遞迴 perl 遍曆 階乘
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‘);
運行結果:
[[email protected] ~]# ./GetResult.pl Result:10 | num:10Result:90 | num:9Result:720 | num:8Result:5040 | num:7Result:30240 | num:6Result:151200 | num:5Result:604800 | num:4Result:1814400 | num:3Result:3628800 | num:2
遍曆linux的檔案目錄找出自己想要的檔案
[[email protected] ~]# 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(‘.‘);
運行結果就是找到檔案或者刪除
perl 遞迴兩例