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

Anyone any ideas why this while loop wont work?

while (open(MYFILE, "$filename") == 0) { printf("Cannot open file for reading"); printf("\n\nDo you wish to enter a new file?: "); $choice = <>; if ($choice eq "no") { die("Program ending"); } if ($choice eq "yes") { print("Enter the name of the file you wish to print: "); $filename = <>; } }

Replies are listed 'Best First'.
Re: While loop wont work
by davido (Cardinal) on Dec 21, 2011 at 00:17 UTC
    • #11940 You said `It doesn't work'. The next violation will be punished by death.

    MJD's Good Advice and Maxims for Programmers.

    By the way, you really should not be trying to write C in Perl. Get a copy of Learning Perl today, read tonight, write Perl in Perl tomorrow.

    One individual already pointed out the chomp issue. I also recommend that you check $! after open to determine if the cause of failure is what you expect. If you wish to handle one potential cause by looping, that's great. But for unrelated causes of failure you would still want to thrown an exception or an alternate handler.


    Dave

Re: While loop wont work
by JavaFan (Canon) on Dec 20, 2011 at 21:17 UTC
    After you've fixed your formatting so we can actually read your code, please explain what "wont work" means. Does it fail to compile? Does it sit on the couch the entire day, drinking beer and watching Jerry Springer? Does it do something, but that something isn't what you expect? Are you suffering from buffering?
Re: While loop wont work
by choroba (Cardinal) on Dec 20, 2011 at 21:16 UTC
    You do not chomp $choice, so it is in fact "yes\n", not "yes".
    Update: misread part of the code. One comment deleted.
Re: While loop wont work
by Khen1950fx (Canon) on Dec 21, 2011 at 04:13 UTC
    I made a few modifications. To my way of thinking, I'm going to use the script to print out a "filename"; hence, you don't really need 'yes' or 'no'. If something comes up, and the user has to scram, then just use a 'q' for 'quit'. Here's what I would do:
    #!/usr/bin/perl -l use strict; use warnings; $|=1; my $filename = ''; until ($filename eq 'q') { print "Enter a filename"; chomp ( $filename = <STDIN> ); }
    This will print filenames until you tell it to quit, but how you want to print those files, I'll leave it up to you.
Re: While loop wont work
by TJPride (Pilgrim) on Dec 21, 2011 at 05:36 UTC
    use strict; use warnings; my $file; while (1) { while (1) { print "Please enter a file name, or Q to quit.\n"; chomp($file = <STDIN>); exit if uc $file eq 'Q'; last if $file; } last if open(FH, $file); print "Can't open $file for read.\n"; } print join '', <FH>; exit;

    FYI - I'm sure this is a homework assignment of some sort, but if you're curious, you -can- print out a file to the screen with the 'cat' command if you're on the Unix or Mac command line. The 'type' command does something similar on Windows, supposedly.