1. always use strict;
2 (related). declare your variables in the appropriate scope
3. your code always prints "Invalid input" even when it is valid -- you want to print that only if they have typed something already.
4. you 'redo FILENAME' without resetting $save, so your while ($save !~ ...) fails the second time through
5. your open/print/close is within the if (-e $save) block, so it never happens if the file does not already exist
6. the {1} in your regular-expressions is useless, since 1 is the default.
7. you could use m/^[SF]$/i to match case-insensitively (/i means ignore-case), but i won't bother with that in the code below..
here is a revised version. i have tried to change as little as possible to make it work, so you can learn from your mistakes rather than be confronted with entirely new/unfamiliar code.
use strict; my $output = "here is some output\n"; # for testing.. your output can + come from whereever my $out; while ( $out !~ m/^[sSfF]$/ ) { print("\nInvalid input.\n Please type either S or F.\n") if $out; print("Do you want to output to (S)creen or to (F)ile?\n"); chomp( $out = <STDIN> ); } if ( $out =~ m/^[sS]$/ ) { print $output; } elsif ( $out =~ m/^[fF]$/ ) { my $save; # this is outside the FILENAME:{} block because it is +needed at the end FILENAME: { while ( $save !~ (m/^[a-zA-Z][a-zA-Z_0-9]*$/) ) { print("\nInvalid input.\n Please begin with a letter and d +o not add extension, it will be added automatically.\n") if $save; print("Please enter filename:\n"); chomp( $save = <STDIN> ); } if ( -e $save ) { my $overwrite; while ( $overwrite !~ (m/^[nNyY]$/) ) { print("\nInvalid input.\n Please type either Y or N.\n +") if $overwrite; print("\nFilename exists. Overwrite? (Y) or (N)\n"); chomp( $overwrite = <STDIN> ); } if ( $overwrite =~ (m/^[nN]$/) ) { undef $save; # reset $save to trigger new prompt! redo FILENAME; } } } open( DATA, ">$save" ) || die "Couldn't open $save for writing: $! +\n"; print DATA $output; close(DATA); }
In reply to Re^3: returning to a loop later on
by mreece
in thread returning to a loop later on
by Yoda_Oz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |