0

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.

Holger Just
  • 52,918
  • 14
  • 115
  • 123

3 Answers3

3
my $s = '';
while ($s eq '') {
    print "put your name:";
    chomp($s = <>);
}
    print "The name you entered is $s \n";
alexmac
  • 239
  • 2
  • 9
Miller
  • 34,962
  • 4
  • 39
  • 60
  • and what's the meaning of chomp function – Nidhal Hack Mar 13 '14 at 18:55
  • 1
    [chomp](http://perldoc.perl.org/functions/chomp.html) removes the return character from the end of a string. Detailed specs available in the linked perldoc page. If you're getting input from the console, you pretty much always want to chomp that data. Could've done it on separate lines though: `$s = <>; chomp $s;` – Miller Mar 13 '14 at 18:56
2

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.

David W.
  • 105,218
  • 39
  • 216
  • 337
  • thnx this one helps me :) – Nidhal Hack Mar 13 '14 at 21:31
  • That won't accept a name of "0". Perhaps you want `while (not defined $name)` or `while (not length $name)`. – Dave Cross Mar 14 '14 at 10:49
  • You're right. But, it will accept [0 but true](http://stackoverflow.com/questions/129945/what-does-0-but-true-mean-in-perl)! The `while ( not length $name )` is a good idea. I'll update my answer. – David W. Mar 14 '14 at 13:13
1
sub readstr {
  while (my $in = <>) {
    chomp $in;
    return $in if length $in;
  }
  "";
}

print "put your name:";
my $s = readstr();
mpapec
  • 50,217
  • 8
  • 67
  • 127