Two examples of Perl recursion

Source: Internet
Author: User



Perl as a text processing language, will naturally have his recursive writing, the younger brother here to share two examples, I hope to be useful to everyone!



Factorial (most classic recursion)


#!/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‘);


Operation Result:


[[email protected] ~]# ./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








Traverse the Linux file directory to find the files you want


[[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(‘.‘);




The result of the operation is to locate the file or delete



Two examples of Perl recursion


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.