Reputation: 85
I want to take a directory path as input from the user in Perl. What is the method to do that?
I tried the below code, but it didn't work:
use strict;
use warnings;
my $abc = "perl";
print "Enter the directory path\n";
my $path = <STDIN>;
mkdir($path/$abc);
Upvotes: 0
Views: 416
Reputation: 851
Please follow the link to understand what permissions are required to create a directory - https://unix.stackexchange.com/questions/331895/required-permission-to-create-directory
Below is an example code that I might use if I have to create a directory structure (the solution is open for feedback):
use strict;
use warnings;
my $abc = "perl";
print "Enter the directory path\n";
my $path = <STDIN>;
# chomp: remove newline from the end of input
chomp $path;
# final directory path
my $dir = "$path/$abc";
# exit if input directory does not exist
unless (-d $path) {
print "$path does not exist, try again\n";
exit 1;
}
# exit if there is no write permission
# write permission is required to create new directory
unless (-w $path) {
print "$path is not writable, try another path\n";
exit 1;
}
# so far, so good, try creating directory
if (mkdir($dir)) {
print "$dir created";
exit 0;
} else {
# if the directory already exist you will get
# Cannot create /opt/perl/perl: File exists
# if there is no execute permission on input directory
# Cannot create /opt/perl/perl: Permission denied
die "Cannot create $dir: $!\n";
}
Upvotes: 0
Reputation: 61937
There are a few errors.
You need to chomp
the input to remove the trailing newline character.
You need to add quotes around the path; otherwise Perl treats /
as division. You likely saw a warning message for that.
You can't use mkdir to create a directory structure. The docs tell you to use mkpath
from File::Path
.
use strict;
use warnings;
use File::Path qw(mkpath);
my $abc = "perl";
print "Enter the directory path\n";
my $path = <STDIN>;
chomp $path;
mkpath("$path/$abc");
Upvotes: 2