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

hey

i am opening a file as

open($fo,"<", $ggg)

and if file does not exist I wish to display a message and exit only when he presses q

so I did this

{ "\n\n$ggg is missing:\nensure that this file is in the working +dir.\nWe are exiting \n\n"; print "Please press q to quit \n"; my $fi = <STDIN>; chomp $fi; if ($fi eq "q" ||$fi eq "Q") { exit; } else { while ($fi) { print "Please press q to quit \n"; $fi = <STDIN>; chomp $fi; if ($fi eq "q" ||$fi eq "Q") { exit() } }

the code is working so that is not the issue , just I wish to know how to give that else statement , i.e. if file does not exist the above code should be executed

Replies are listed 'Best First'.
Re: file dies instantly
by rjt (Curate) on Jul 24, 2013 at 13:14 UTC

    See open, -X, and $!.

    if (not -e $filename) { say "`$filename' does not exist"; # Your code here. However, see perldoc -f -X # for additional test operators you will # probably want to use in addition to "exists" } # OR my $fh; if (not open $fh, '<', $filename) { say "Could not open `$filename': $!"; # Your code here. }
Re: file dies instantly
by choroba (Cardinal) on Jul 24, 2013 at 13:16 UTC
    open returns true if it was successful:
    if (open my $fo, '<', $ggg) { # Process the file. } else { # Your code to exit. }

    Update: Also note that parts of your code are repeated. That is against the DRY principle. Better:

    { print "'$ggg' is missing:\nEnsure that this file is in the working + dir.\nWe are exiting.\n"; my $answer; while ('q' ne lc $answer) { print "Please press 'q' and Enter to quit\n"; chomp($answer = <STDIN>); } exit; }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: file dies instantly
by kcott (Archbishop) on Jul 24, 2013 at 13:21 UTC

    Firstly, die with a message is preferable to exit.

    I don't really see where the { "\n\n$ggg ... block fits in with either open or whatever (undisclosed) code surrounds it. The open documentation shows examples of using die.

    As an alternative, take a look at the autodie pragma.

    -- Ken

      Furthermore, if you use die you can add a sub reference into $SIG{__DIE__} (see die's documentation) that will be called just before the error processing is done. Which means you can add that "wait for user input" behaviour for several die calls at once. You can limit that modification to a dynamic scope with local.

      Be sure not to call exit in the sub that will be called when dieing, or else you might just as well have never died.