in reply to Syntax error when trying to use a hash value as a file stream specifier

G'day Fireblood,

In the examples below, I've used a common alias of mine which picks up many problems:

$ alias perle alias perle='perl -Mstrict -Mwarnings -Mautodie=:all -MCarp::Always -E +'

Probably the first thing to note is that filehandles are globrefs. Here's an example (along with a hashref for comparison).

$ perle 'open my $fh, ">", "not_a_file"; say "$fh"; unlink "not_a_file +";' GLOB(0x8000c42e0) $ perle 'my $hashref = {}; say "$hashref";' HASH(0x800003bc8)

Had you used the strict pragma, you would have seen:

Bareword "STDERR" not allowed while "strict subs" in use ...

Always start your code with the following:

use strict; use warnings;

or code that gives you one or both of those (e.g. use v5.12 gives you strict; use v5.36 gives you strict and warnings; various modules have similar effects):

The next question might be, what should you use instead of STDERR? I'd argue that \*STDERR is strictly correct as it's a globref; however, *STDERR will also work.

$ perle 'my $x = \*STDERR; say "$x";' GLOB(0x80008fcd0) $ perle 'my $x = *STDERR; say "$x";' *main::STDERR

That finally brings us to how to use the hash value without an intermediate scalar value. You have two main options (perhaps others will suggest additional ones).

Side note: All of the above examples were run using Perl v5.36. This version disables the indirect feature by default (see "perl5360delta: use v5.36"). Obviously, the filehandle case is still allowed; however, if you do use that syntax elsewhere (e.g. my $obj = new Class ...), you may want to consider getting out of the habit of doing so.

— Ken