What are the differences between this two examples?
#!/usr/bin/perl
use warnings;
use 5.012;
my $str = "\x{263a}";
open my $tty, '>:encoding(utf8)', '/dev/tty' or die $!;
say $tty $str;
close $tty;
open $tty, '>:bytes', '/dev/tty' or die $!;
say $tty $str;
close $tty;
# -------------------------------------------------------
binmode STDOUT, ':encoding(utf8)' or die $!;
say $str;
binmode STDOUT, ':bytes' or die $!;
say $str;
The difference is that you are writing to two distinct and (from Perl's and your program's point of view) independent file handles.
The first one is a file handle opened to a special "device" file on Unixy OS which is "a synonym for the controlling terminal of a process, if any" (quote from this Linux document). Please note that while it is commonly thought of as "screen", it doesn't have to be (e.g. that terminal could be linked to a serial port's device file instead); and it may not exist or not be openable.
The second one is a file handled associated by default with file descriptor #1 for the process.
They may SEEM to be identical at first glance due to the fact that, in a typical situation, a Unix shell will by default associate its file descriptor #1 (and thus one of every process it launches without redirects) with /dev/tty
.
The two have nothing in common from Perl point of view, OTHER than the fact that those two commonly end up associated by default due to the way Unix shells work.
The functional behavior of the two quoted pieces of code will often SEEM identical due to this default, but that is just "by accident".
Among practical differences:
/dev/tty
does not necessarily exist on non-Unixy OSs. It's therefore highly un-portable to use tty. Windows equivalent is CON:
IIRC.
STDOUT
of a program can be associated (re-directed) to ANYTHING by whoever called the program. Could be associated to a file, could be a pipe to another process's STDIN.
You can CHECK whether your STDOUT is connected to a tty by using the -t
operator:
if ( -t STDOUT ) { say 'STDOUT is connected to a tty' }
As another aside, please note that you CAN make sure that your STDOUT writes to /dev/tty
by explicitly closing the STDOUT filehandle and re-opening it to point to /dev/tty
:
close STDOUT or die $!;
open STDOUT '>:encoding(utf8)', '/dev/tty' or die $!;
In addition to what DVK said, you can see the simple difference by saying
perl -le 'open $o, ">:encoding(utf8)", "/dev/tty"; print "STDOUT"; print $o "/dev/tty"' > /dev/null
The write to STDOUT
goes to /dev/null
, but the write to $o
goes to the screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With