1

I am trying to keep my command prompt from closing when there is an error in opening a file. I already tried the 'die' command, but that closes the command prompt right after the message is displayed. I want to be able to print an error message, wait a few seconds, then close or exit. Right now, I can get the code to wait before closing the prompt, but it never displays my error message:

open (LOG1, $file1) || (print "\n# Error in opening $file1, make sure it exists! #\n", sleep(3), exit);
1
  • 1
    This is only an issue if you're running your perl script as the main process in a window. Using Windows? If so, you might want Win32::Die
    – Wooble
    Jul 22, 2011 at 13:09

3 Answers 3

6

You're misusing the comma operator - print doesn't print the error message, but the return value of exit()! Use semicolons instead.

3

I think you are developing using a Windows system. If so, you can try adding the following code in your script which will display: 'Press any key to continue ...' just before the script exits.

END { system 'pause' }
2

I suspect that sleep does no flush the output buffer, so that could explain why you don't see anything printed out; you could try:

open (LOG1, $file1) || ((print "\n# Error in opening $file1, make sure it exists! #\n"), $|++, sleep(3), exit);

In any case, it seems to me that it would be much preferable to define a dieAfterDelay function like this:

sub dieAfterDelay {
    my $msg = shift;
    my $delay = shift;
    my $errNo = shift;
    print $msg . "\n", $|++;
    sleep($delay);
    exit($errNo);
}

that you could use like this:

open (LOG1, $file1) || dieAfterDelay("\n# Error in opening $file1, make sure it exists! #\n", 3, -1);
3
  • 1
    $| If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Jul 22, 2011 at 13:22
  • What does it do in this example, specifically?
    – Stephen D
    Jul 22, 2011 at 13:30
  • What it does is flushing the output buffer right after the print statement. That was just a try...
    – sergio
    Jul 22, 2011 at 13:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.