Re: goto???



Shiping Wang wrote:
Hello,

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?

-------------------------------------------------------------------------------------------------------------------------------------------

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 - $!";

How about this:

my $file = 'sumpower.txt';

STARTOVER:
while ( -e $file ) {
warn "The summary file already exists! ",
"Would you like to give it another name? (y/n)\n",
"If your answer is 'n' then the file will be overwritten. ",
"What's your decision?\n";

ANSWER:
{ my $answer = <STDIN>;
if ( $answer =~ /^y/i ) {
print "What's the new file name?\n";
chomp( $file = <STDIN> );
next STARTOVER;
}
elsif ( $answer =~ /^n/i ) {
# unlink not required as open will overwrite the file.
last STARTOVER;
}
else {
print "You have given a invalid answer, try again (y/n)\n";
redo ANSWER;
}
}
}

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



John
--
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order. -- Larry Wall
.



Relevant Pages

  • Re: goto???
    ... then ask user to change file name or override it. ... goto STARTOVER; ... You don't need to unlink the existing file, '>' will overwrite it. ... chomp $answer; ...
    (perl.beginners)
  • [PATCH/RFC 4/8] crypto: api - Add type init function to crypto_tfm
    ... Add a type init function to crypto_tfm, so transforms can override the default ... action of calling the algorithm's cra_initmethod. ... if (err) ... goto out_free_tfm; ...
    (Linux-Kernel)