perl function readline

‮gi.www‬iftidea.com

The readline function in Perl is used to read a line from a filehandle or from standard input.

Here's an example that demonstrates the use of readline to read from a filehandle:

open(my $fh, '<', 'example.txt') or die "Could not open file 'example.txt' $!";
while (my $line = readline($fh)) {
  chomp $line;
  print "Line: $line\n";
}
close($fh);

In this example, we first open a file example.txt in read mode using the open function. We then loop through each line of the file using the readline function, which reads a single line from the filehandle pointed to by $fh. The chomp function is used to remove the newline character from the end of each line, and we then print out the line with the print function.

If you wanted to use readline to read from standard input, you can simply omit the filehandle argument:

print "Enter some text: ";
while (my $line = readline()) {
  chomp $line;
  last if $line eq 'quit';
  print "You entered: $line\n";
  print "Enter some more text (or 'quit' to exit): ";
}

In this example, we prompt the user to enter some text using the print function. We then use readline without any arguments to read a line from standard input. We then check if the user entered the string "quit", and if so, we exit the loop using the last statement. Otherwise, we print out the line using the print function, and prompt the user to enter more text.