Perl: built-in FD selection, as in docs, does not work with strict refs

In perldoc forprint , he says this should work:

print { $OK ? STDOUT : STDERR } "stuff\n";

But this is not with use strict, and when I then use quotation marks like

print { $OK ? "STDOUT" : "STDERR" } "stuff\n";

I get

Can't use string ("STDOUT") as a symbol ref while "strict refs" in use ...

How can I make this structure work without performing use strict?

Thank,

Mazze

+4
source share
2 answers

Try the following:

print { $OK ? *STDOUT : *STDERR } "stuff\n";

An asterisk means type glob. Since there are no pigments to indicate a file descriptor, you should instead use the sigil typeglob character, an asterisk.

+7
source

To prevent the error message Bareword "STDOUT" not allowed while "strict subs" in use at ..., you will need to use typeglob:

#!/usr/bin/perl

use strict ;
use warnings ;

my $OK = 1 ;

printf { $OK ? *STDOUT : *STDERR } "stuff\n" ;
+5
source

Source: https://habr.com/ru/post/1670934/


All Articles