Nidhal Hack
Nidhal Hack

Reputation: 1

How can I stop my script instead of progressing

I did a simple script using perl and I was wondering how I can pause the program or return it to the action before? I have this code

print "put your name:";
$s=<>;

and it didn't output anything. I want the program to repeat the same action, i.e. asking the user to enter his name instead of progressing.

Upvotes: 0

Views: 81

Answers (3)

David W.
David W.

Reputation: 107090

No need to set $name to anything before you start - just define it:

my $name;
while ( not length $name ) {  #Thx Dave Cross
    print "What is your name? ";
    $name = <STDIN>;
    chomp $name;
}

In Perl, variables defined with my (and that should be 99% of your variables) have a limited scope. If they're defined in a block (something that uses curly braces like this while loop), they'll lose their value once they leave the block. That's why I have to have my $name; before the while.

The while ( not $name ) { will work if $name isn't defined or is a null value, so this will loop until I enter something into $name that's not null.

The chomp removes the NL character that I enter when I press the <ENTER> key. You should always chomp your variables after a read of any sort. Just get use to it.

In this form, the loop is self documenting. I am looping while $name isn't filled in.

You can combine the chomp with the input like this:

my $name;
while ( not $name ) {
    print "What is your name? ";
    chomp ( $name = <STDIN> );
}

Some people like this because it's a bit shorter, but I don't know if its any clearer. I'm a fan of code clarity because it's easier to maintain.

Upvotes: 2

Miller
Miller

Reputation: 35208

my $s = '';
while ($s eq '') {
    print "put your name:";
    chomp($s = <>);
}
    print "The name you entered is $s \n";

Upvotes: 3

mpapec
mpapec

Reputation: 50667

sub readstr {
  while (my $in = <>) {
    chomp $in;
    return $in if length $in;
  }
  "";
}

print "put your name:";
my $s = readstr();

Upvotes: 1

Related Questions