尝试循环直到用户提供有效目录:
my $src;
#1. Get source directory
do {
print "Enter the Source Directory of .md Files (eg. /home/user/notes): \n";
chomp($src = <>);
#make sure directory exists
until (-e $src and -d $src);
我想显示以下消息:
print "[ERROR] Invalid Directory Given...Please try again\n";
until
条件失败时。
我怎样才能这样做(没有大量的代码)?
旁注:如果有一种语言允许更好(更优雅)处理此问题,请分享
答案 0 :(得分:3)
我喜欢Term::UI
来创建用户提示,因为它允许您提供默认值,验证输入和其他漂亮的功能:
use strict;
use warnings;
use 5.010;
use Term::ReadLine;
use Term::UI;
my $term = Term::ReadLine->new('path');
$Term::UI::INVALID = 'Not a valid directory, please try again: ';
my $path = $term->get_reply(
prompt => 'Enter the Source Directory of .md Files',
default => '/root',
allow => sub { return -d $_[0] }
);
say $path;
默认值为/root
;要使用默认值,您只需在提示符处按 Enter 即可。
Enter the Source Directory of .md Files [/root]: /foo
Not a valid directory, please try again: [/root] /home
/home
答案 1 :(得分:1)
my $src;
#1. Get source directory
while(1) {
print "Enter the Source Directory of .md Files (eg. /home/user/notes): \n";
chomp($src = <>);
if (-e $src and -d $src) {
last;
} else {
print "[ERROR] Invalid Directory Given...Please try again\n";
}
}
答案 2 :(得分:1)
所以你想要一个看起来像
的循环代码:
while (1) {
print "Enter the Source Directory of .md Files (eg. /home/user/notes): ";
$src = <>;
die if !defined($src);
chomp($src);
last if -d $src;
print "[ERROR] Invalid Directory Given...Please try again\n";
}