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

Today I came across what seems to this newbie a quite perplexing puzzle. It regards the behaviour of references to filehandles:

#!/usr/bin/perl -w use strict; open(OUTFILE, ">out.txt") or die "cannot open out.txt: $!"; my $fred = {}; $fred->{outfile} = \*OUTFILE; my $barney = $fred->{outfile}; print $barney "This is a test\n"; print $fred->{outfile} "This is another test\n";

The code above produces the following syntax error:

String found where operator expected at ./test.pl line 11, near "} "Th +is is another test\n"" (Missing operator before "This is another test\n"?) syntax error at ./monks.pl line 11, near "} "This is another test\n"" Execution of ./test.pl aborted due to compilation errors.

My question is why does it work for $barney, but not for $fred->{outfile}, when both should contain the same reference?

Thanks in advance for any light you may be able shed upon this matter.

Replies are listed 'Best First'.
Re: Using a reference to a Filehandle
by artist (Parson) on Jul 09, 2003 at 05:49 UTC
    From perldoc -f print or print: Note that if you're storing FILEHANDLES in an array or other expression, you will have to use a block returning its value instead.

    Following should work:
    print {$fred->{outfile}} "This is another test\n";

    artist

      Thank-you for your response, your suggestion does indeed work.