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 = ); } 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 do not add extension, it will be added automatically.\n") if $save; print("Please enter filename:\n"); chomp( $save = ); } 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 = ); } 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); }