On 10/27/06, Shiping Wang <[EMAIL PROTECTED]> wrote:
Hello,  I try to use following code to check if a file is already exist, if
it exists, then ask user to change file name or override it. I know using
'goto' is not preferred way here, but what's the 'right way' to do so?

Thanks,

Shiping

-------------------------------------------------------------------------------------------------------------------------------------------
my $file = "sumpower\.txt";

        if (-e $file ){
                warn "The summary file already exist! Wold you like to give 
another name?
(y/n)\n".
                     "If your answer is 'n' then the file will be overrided. 
What's your
decision?\n";
STARTOVER:
                     my $answer = <STDIN>;
                     if ($answer =~ /y/i){
                             print "What's the new file name?\n";
                             $file = <STDIN>;
                     }elsif ($answer =~ /n/i){
                             unlink $file;
                     }else {
                             print "You have given a invalid answer, try again 
(y/n)\n";
                             goto STARTOVER;
                     }
        }

        open(OUT, "> $file") or die "Cannot open $file - $!";


First, a couple of general notes:
   1) You don't need to unlink the existing file, '>' will overwrite it.
   2) You don't need to escape '.' in double quoted strings.
   3) You should check to make sure the new file doesn't exist.
   4) You don't define an action if the answer to "start over?" is
no, so don't ask, just do it.
   5) You should echo $file so that the user doesn't try to enter the
same name.

With that in mind:


my $file = "sumpower.txt";
while (1) {
   last unless -e $file;
   warn <<'    EOF';
   The summary file $file already exists! Wold you like to give
another name? (y/n).
   If your answer is 'n' then the file will be overwritten.
   What is your decision?

   EOF
   my $answer = <STDIN>;
   chomp $answer;
   last if $answer =~ /^n$/i;
   if ( $answer =~ /^y$/i ) {
       print "What's the new file name?\n";
       $file = <STDIN>;
       chomp $file;
   } else {
       print "You have given a invalid answer. try again";
   }
}
open($OUT, ">", $file) or die "Can't open summary file $file for writing: $!\n";


HTH,

--jay
--------------------------------------------------
This email and attachment(s): [  ] blogable; [ x ] ask first; [  ]
private and confidential

daggerquill [at] gmail [dot] com
http://www.tuaw.com  http://www.downloadsquad.com  http://www.engatiki.org

values of β will give rise to dom!

Reply via email to