edimusrex has asked for the wisdom of the Perl Monks concerning the following question:

My issue should be simple but it's driving me crazy. What I am doing is trying to verify whether or not a folder path exists by reading a users input. Here is what I have now but it returns nothing

print "What do you want to save?\n"; my $inp = <>; $inp =~ s/\\/\//g; if ($inp !~ m/^\w+$|^.+$/g) { do { print "Nothing Entered. Try Again - "; $inp = <>; } until ($inp =~ m/^\w+$|^.+$/g) } if ( -d $inp) { print "Folder exists! - \n" }

I eventually would like to verify a file but for now the directory is all I need. Any help would be appreciated

Replies are listed 'Best First'.
Re: Verifying If a directory exists
by moritz (Cardinal) on Feb 23, 2012 at 17:43 UTC

      Ah, perfect...so easy. Corrected by adding chomp to the scalar. Thanks!

Re: Verifying If a directory exists
by Marshall (Canon) on Feb 23, 2012 at 18:20 UTC
    Another way of writing the command loop...
    If the user doesn't enter a non-blank line, then just a simple reprompt is usually sufficient - they figure out why you are asking the question again very quickly! Also as a general rule for the command line, leading and trailing white space is allowed.
    #!/usr/bin/perl -w use strict; while ( (print "Enter Directory for saving: "), my $input = <STDIN> ) { next if $input =~ /^\s*$/; # simple reprompt if blank line $input =~ s/^\s*//; # trim leading blanks $input =~ s/\s*$//; # trim trailing blanks # also does an implicit "chomp" if (-d $input) { print "DirectoryPath: $input already exists!\n"; next; #this causes a reprompt.. } print "processing directory $input\n"; last; }
Re: Verifying If a directory exists
by JavaFan (Canon) on Feb 23, 2012 at 20:13 UTC
    m/^\w+$|^.+$/g
    Considering that anything that's matched by /^\w+$/ will also be matched by /^.+$/, you might as well write /^.+$/. Having said that, the only strings that don't match are the string "\n" and any string that contains a newline that doesn't end the string itself. I don't see a reason to check for internal newlines -- they're a bitch to enter (and unlikely to happen by accident), and people usually don't put them in directory names anyway. So, I'd just chomp (you want to do that anyway), and check if the result is different from the empty string.

    Also note the /g modifier. This has side-effects. I don't think they will hurt you in this particular case, but a next time, you may get bitten by such careless usage.