Perl 5 version 26.3 documentation

readline

  • readline EXPR
  • readline

    Reads from the filehandle whose typeglob is contained in EXPR (or from *ARGV if EXPR is not provided). In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns undef. In list context, reads until end-of-file is reached and returns a list of lines. Note that the notion of "line" used here is whatever you may have defined with $/ (or $INPUT_RECORD_SEPARATOR in English). See $/ in perlvar.

    When $/ is set to undef, when readline is in scalar context (i.e., file slurp mode), and when an empty file is read, it returns '' the first time, followed by undef subsequently.

    This is the internal function implementing the <EXPR> operator, but you can use it directly. The <EXPR> operator is discussed in more detail in I/O Operators in perlop.

    1. my $line = <STDIN>;
    2. my $line = readline(STDIN); # same thing

    If readline encounters an operating system error, $! will be set with the corresponding error message. It can be helpful to check $! when you are reading from filehandles you don't trust, such as a tty or a socket. The following example uses the operator form of readline and dies if the result is not defined.

    1. while ( ! eof($fh) ) {
    2. defined( $_ = readline $fh ) or die "readline failed: $!";
    3. ...
    4. }

    Note that you have can't handle readline errors that way with the ARGV filehandle. In that case, you have to open each element of @ARGV yourself since eof handles ARGV differently.

    1. foreach my $arg (@ARGV) {
    2. open(my $fh, $arg) or warn "Can't open $arg: $!";
    3. while ( ! eof($fh) ) {
    4. defined( $_ = readline $fh )
    5. or die "readline failed for $arg: $!";
    6. ...
    7. }
    8. }