enia sharmila
enia sharmila

Reputation: 1

Auto create missing folder with perl

Hi im very new to programming and perl , I badly need help. Requirement : Currently creating an auto folder creating also with subfolder if wrongly delete. To call the subfolder I did not hard code, all sub folder consist of 9. So use "for" loop function and "array" to make sure all the subfolder exist once folder is deleted.

#!/usr/bin/env perl
use strict;
use warnings;

my $dirname = "/srv/ym/home/ymadm/transfer/ymtrans/YM/sharmila";
my $dirname1 = '/srv/ym/home/ymadm/transfer/ymtrans/YM/sharmila/';

my @folder = qw(test1 test2 abc def efg);
my $exists = ` if [ -d '$dirname' ] ; then echo 1; else echo 0; fi `;
$exists =~ s/\n$//;
    if ($exists eq '1')
    {
            print "exists";

    }
    else
    {
        unless(mkdir($dirname, 0777)) 
        {
            die "Unable to create $dirname\n";
        }

    chmod(0777, $dirname) or die "Couldn't chmod $dirname: $!";


        for(my $i = 1; $i <= 5; $i = $i + 1 ) 
        {

            unless(mkdir($dirname1.$i.@folder, 0777)) 
            {
                die "Unable to create $dirname1\n";
            }



            chmod(0777, $dirname1.$i.@folder) or die "Couldn't chmod $dirname1.$i: $!";
        }    


    }
print "\n";

Upvotes: 0

Views: 164

Answers (1)

choroba
choroba

Reputation: 241968

No need to shell out for -d, Perl has the same operator.

To create a path with all the missing parts recreated, use make_path from File::Path:

#!/usr/bin/env perl
use strict;
use warnings;
use feature qw{ say };

use File::Path qw{ make_path };

my $dirname  = "/srv/ym/home/ymadm/transfer/ymtrans/YM/sharmila";
my @folders  = qw( test1 test2 abc def efg );

my $fullpath = join '/', $dirname, @folders;

if (-d $fullpath) {
    say 'Exists.';
} else {
    make_path($fullpath);  # mode => 0777 is the default
    say 'Created.';
}

Upvotes: 1

Related Questions