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.