I/O

print#

Write a list of values to a filehandle.

print is the everyday output primitive. It stringifies each item in LIST, joins them with the current value of $, (the output field separator, usually empty), writes them to FILEHANDLE, and finally appends $\ (the output record separator, usually empty). If FILEHANDLE is omitted, output goes to the currently selected handle (see select), which defaults to STDOUT. If LIST is omitted, $_ is printed.

Synopsis#

print LIST
print FILEHANDLE LIST
print {EXPR} LIST
print

What you get back#

1 on success, undef on failure (with $! set). The return value is rarely checked — most print calls target STDOUT or STDERR and a write failure to either is already a program-ending condition. Check the return value when writing to a file, pipe, or socket where partial writes and broken pipes matter.

print $fh @records
    or die "write to $path failed: $!";

Default filehandle, default separators#

Three pieces of global state shape every print call:

  • The currently selected filehandle, changed with select. print LIST (no explicit filehandle) writes there. At program start this is STDOUT.

  • $,output field separator, inserted between list items. Default is the empty string, so print 1, 2, 3 produces 123, not 1 2 3. Also known as $OFS under use English.

  • $\output record separator, appended after the whole list. Default is the empty string, so print does not add a newline. Also known as $ORS under use English.

Setting both gives Python-like print semantics:

local $, = " ";
local $\ = "\n";
print 1, 2, 3;          # "1 2 3\n"

Use local when changing these inside a subroutine so the change does not leak to the caller.

say is exactly print with $\ forced to "\n" for that one call — reach for it when you want a newline every time and do not want to touch $\.

Examples#

Basic write to STDOUT:

print "hello, world\n";

Write to a filehandle with the indirect-object form. Note: no comma between the filehandle and the list:

open my $fh, ">", "out.txt" or die $!;
print $fh "line 1\n", "line 2\n";
close $fh;

Write to a filehandle held in an expression. Any filehandle more complex than a bareword or a plain scalar needs the {EXPR} block form:

my @logs = (\*STDOUT, \*STDERR);
print { $logs[$level] } "message\n";

Join list items with $, and terminate the record with $\:

local $, = ", ";
local $\ = ".\n";
print "apples", "pears", "plums";   # "apples, pears, plums.\n"

A list containing undef — each undef stringifies to the empty string and triggers an uninitialized warning under use warnings:

use warnings;
my $x;
print "value=", $x, "\n";           # "value=\n" plus a warning

List context vs scalar context. @arr in LIST position expands to its elements; wrap in scalar to print the count instead:

my @arr = (10, 20, 30);
print @arr, "\n";                   # "102030\n"
print scalar @arr, "\n";            # "3\n"

Suppressing the undef warning for a block where missing values are expected and intended to render as empty:

no warnings 'uninitialized';
print join(",", @row), "\n";        # empty fields render as ""

Edge cases#

  • No arguments: print; prints $_ to the selected handle. Used idiomatically inside while (<>) { print; }.

  • The filehandle-or-first-arg ambiguity: Perl decides whether the first token is a filehandle by parsing, not by runtime type. A bareword or a simple scalar variable immediately followed by a term (no comma) is taken as a filehandle:

    print STDERR "oops\n";            # STDERR is the filehandle
    print $fh "oops\n";               # $fh is the filehandle
    

    An expression that returns a filehandle does not work in that position — print $handles[0] "x" is a syntax error. Use the block form: print { $handles[0] } "x".

  • List context applies to every argument. A subroutine call in LIST runs in list context, not scalar:

    print localtime(), "\n";          # prints nine numbers, no spaces
    print scalar localtime(), "\n";   # prints the familiar date string
    
  • print (…) parses as a function call. print (2+3)*4 prints 5, then discards *4. Parenthesise the whole argument list, or prefix with +:

    print((2+3)*4);                   # prints 20
    print +(2+3)*4;                   # prints 20
    
  • Closed filehandle: returns undef and sets $! to "Bad file descriptor". Under use warnings a print() on closed filehandle warning is emitted.

  • Encoding layers: print writes whatever the handle’s PerlIO stack says to write. If the handle has a :utf8 or :encoding(...) layer, strings are encoded on the way out. Bytes-mode handles expect byte strings; passing a wide-character string writes raw codepoints and emits a Wide character in print warning.

  • Autoflush: print buffers through PerlIO. Set $| on the selected handle to flush after every write — commonly needed for progress output on pipes or when coordinating with another process:

    $| = 1;                           # autoflush current handle
    
  • Printing to a closed pipe or socket raises SIGPIPE. The default action is to terminate the process; install a handler ($SIG{PIPE} = 'IGNORE' or a sub) to turn it into a normal write failure you can check.

Differences from upstream#

Fully compatible with upstream Perl 5.42.

See also#

  • sayprint with $\ forced to "\n" for the call; use it when every record ends in a newline

  • printf — same targeting rules as print, but the first argument is a sprintf format string and $\ is not appended

  • sprintf — build the formatted string without writing it; combine with print when you want to log it somewhere else first

  • select — change which filehandle the no-argument form of print writes to

  • $, — output field separator inserted between list items

  • $\ — output record separator appended after the list

  • $| — autoflush flag for the currently selected handle