Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

The following piece of code works exactly as I would expect:
#!/usr/bin/perl use strict; use warnings; my $f=\*stdout; my $h={}; $h->{FILE}=$f; print $f "Hello\n";
But this doe not, it gives a syntax error:
#!/usr/bin/perl use strict; use warnings; my $f=\*stdout; my $h={}; $h->{FILE}=$f; print $h->{FILE} "Hello\n";
The only change is that I use an expression involving hashref for the file handle in the second case rather than a variable. Is this not allowed?

Replies are listed 'Best First'.
Re: Unexpected results with expression for file handle in print
by tobyink (Canon) on Feb 13, 2014 at 10:24 UTC

    Use this:

    print {$h->{FILE}} "Hello\n";

    Perl only understands very simple expressions as filehandles, but you can wrap more complex expressions in braces. This is covered in the documentation for print.

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name