Creating a folder using perl

I want to create a folder using perl where the same perl script folder exists. I created FolderCreator.pl, which requires a folder name of input parameters.

unless(chdir($ARGV[0]){ # If the dir available change current , unless
    mkdir($ARGV[0], 0700);                             # Create a directory
    chdir($ARGV[0]) or die "can't chdir $ARGV[0]\n";    # Then change or stop
}

This worked fine only if we call scipt in the same folder it is in. If it calls another folder, if it does not work.

Eg.

.../Scripts/ScriptContainFolder> perl FolderCreator.pl New
.../Scripts> perl ./ScriptContainFolder/FolderCreator.pl New

The first is working, but the second is not. Is there any way to create these folders?

+3
source share
3 answers

I did this work, and here is the code ... Thanks to everyone for their help ...

#!usr/bin/perl

###########################################################################################
# Needed variables
use File::Path;
use Cwd 'abs_path';
my $folName     = $ARGV[0];
#############################################################################################
# Flow Sequence 
if(length($folName) > 0){
    # changing current directory to the script resides dir
    $path = abs_path($0);
    $path = substr($path, 0, index($path,'FolderCreator.pl') );
    $pwd = `pwd`;
    chop($pwd);
    $index = index($path,$pwd);
    if( index($path,$pwd) == 0 ) {
        $length = length($pwd);
        $path = substr($path, $length+1);

        $index = index($path,'/');
        while( $index != -1){
            $nxtfol = substr($path, 0, $index);
            chdir($nxtfol) or die "Unable to change dir : $nxtfol"; 
            $path = substr($path, $index+1);
            $index = index($path,'/');
        } 
    }
    # dir changing done...

    # creation of dir starts here
    unless(chdir($folName)){        # If the dir available change current , unless
        mkdir("$USER_ID", 0700);    # Create a directory
        chdir($folName) or $succode = 3;    # Then change or stop
    }
}
else {
    print "Usage : <FOLDER_NAME>\n";    
}
exit 0;
+1
source

You can use the FindBin module , which gives the $ Bin variable. It finds the full path to the bin script directory to allow the use of paths relative to the bin directory.

use FindBin qw($Bin);

my $folder = "$Bin/$ARGV[0]";

mkdir($folder, 0700) unless(-d $folder );
chdir($folder) or die "can't chdir $folder\n";
+5

, , , , , chdir.

unless(chdir($ARGV[0])) {   #fixed typo
    mkdir($ARGV[0], 0700);
    chdir($ARGV[0]) or die "can't chdir $ARGV[0]\n";
}

script :

  • script can not chdir $ARGV [0] :
  • $ARGV [0], 0700.
  • $ ARGV [0] script "can not chdir..".

script , , , . * nix, $ENV{PWD} script. , .

, . , , :

.../Scripts> perl ./ScriptContainFolder/FolderCreator.pl ScriptContainFolder/New

,

?> FolderCreator.pl /home/m/me/Scripts/ScriptContainFolder/New

ETA: , , , , , , :

use strict;
use warnings;
+3

All Articles