Arianule
Arianule

Reputation: 9053

Exiting loop using regular expression in Perl

I am appending information to a text file and want to do this until exit is entered as a string.

This is what I used but 'exit' does not want to exit the loop.

print "please input info to write to the file\n";
my $input = <STDIN>; 
until($input =~ /exit/)
{
    open MYFILE, ">>information.txt" or die "$!";
print MYFILE "$input";

print "enter 'exit' to exitor add more info\n";
my $input = <STDIN>;
}

Upvotes: 0

Views: 141

Answers (2)

Konerak
Konerak

Reputation: 39773

You are making a few mistakes here, but as parapura said, only one causes this particular bug.

print "Please input info to write to the file\n";
my $input = <STDIN>; 
#Three argument open is better than a global filehandle
open (my $handle, '>>', 'information.txt') or die "$!";
until($input =~ /^exit$/) { #Better with ^$, else 'fireexit' will end the loop as well.
    print $handle $input;
    print "Enter 'exit' to exit or add more info\n";
    #Remove the 'my', else it is another variable than the one in the until clause
    $input = <STDIN>;
}
close ($handle) or die "$!";

Upvotes: 1

parapura rajkumar
parapura rajkumar

Reputation: 24413

One of your $input is hiding the other one. Remove the my from the second one.

Upvotes: 2

Related Questions