vaindil
vaindil

Reputation: 7844

Terminating while loop with empty stdin in Perl

I'm running a while loop in a Perl script that needs to terminate when nothing is entered for stdin. I've tried all kinds of possibilities, most recently while($in ne ""), but nothing works. What is the correct way to terminate a while loop if the given condition (stdin) is simply nothing (just enter is pressed at the prompt)?

EDIT: To clarify, I need a loop similar to the below code, and I need to terminate the while loop if nothing is entered for the prompt.

print "Enter your information: ";
$in = <>;

while($in) {
    #do stuff

    print "Enter your information: ";
    $in = <>;
}

Upvotes: 0

Views: 1307

Answers (5)

robmuh
robmuh

Reputation: 25

Try this

#!/usr/bin/env perl

use warnings;
use strict;

my $in = '';
while (1) {
  print "Enter your information: ";
  $in = <STDIN>;

  ##  do something with $in, I assume

  last if $in =~ /^\s*$/;     # empty or whitespace ends
}

But you might be trying to append the lines in which case change

$in = <STDIN>;

To

$in .= <STDIN>;

Or chomp it and add.

Or maybe you are looking more generally for a way to filter interactive prompts:

#!/usr/bin/env perl

use warnings;
use strict;

sub prompt {
  my ($text, $filter) = @_;
  while (1) {
    print $text;
    my $entry = <STDIN>; 
    chomp $entry;
    return $entry if $entry =~ $filter;
  }
}

prompt "Enter a digit: ", qw/^\d$/;

Upvotes: 0

Borodin
Borodin

Reputation: 126722

I think you are looking for this

while () {

  print "Enter your information: ";
  chomp(my $in = <>);
  last unless $in;

  # do stuff with $in
}

Upvotes: 0

mpapec
mpapec

Reputation: 50637

while (my $in = <>) {

  chomp($in);
  length($in) or last;

  # ..
}

Upvotes: 4

Miller
Miller

Reputation: 35198

The other two answers already have you covered, but to more completely duplicate your code, you can do the following:

use strict;
use warnings;

while (1) {
    print "Enter your information: ";
    my $in = <STDIN>;
    chomp($in);

    last if $in eq '';
}

Upvotes: 2

plu
plu

Reputation: 1351

while (my $in = <STDIN>) {
    print "got: '$in'\n";
    chomp($in);
    last if $in eq '';
}

print "done.\n"

Upvotes: 1

Related Questions