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

I'm having issues with file handles stored as a scalar element within a anonymous hash. Example #1 below is a working beginning point and has a scalar $fh holding the opened file handle... It works, no problem.
EXAMPLE #1
use strict; MAIN: { my $fh; open($fh, ">hdt.html") or die("Unable to open output file!"); my $title = 'MY TTILE'; print $fh <<EOF; <html> <head> <title>$title</title> </head> <body> Blah, Blah... </body> </html> EOF close $fh; }
Example #2 below now opens the file handle into a scalar value of an anonymous hash referenced by $args...
EXAMPLE #2
use strict; MAIN: { my $args = {}; open($args->{fh}, ">hdt.html") or die("Unable to open output file! +"); my $title = 'MY TTILE'; print $args->{fh} <<EOF; <html> <head> <title>$title</title> </head> <body> Blah, Blah... </body> </html> EOF close $fh; }
And the following compile time error results!
D:\Development\Perl\HereDocTest>hdt2.pl<br> Scalar found where operator expected at D:\Development\Perl\HereDocTes +t\hdt2.pl line 10, near "<title>$title"<br> (Missing operator before $title?)<br> Bareword found where operator expected at D:\Development\Perl\HereDocT +est\hdt2.pl line 11, near "</head"<br> (Might be a runaway multi-line // string starting on line 10)<br> (Missing operator before head?)<br> Bareword found where operator expected at D:\Development\Perl\HereDocT +est\hdt2.pl line 13, near "Blah"<br> (Missing semicolon on previous line?)<br> syntax error at D:\Development\Perl\HereDocTest\hdt2.pl line 9, near " +head>"<br> Search pattern not terminated at D:\Development\Perl\HereDocTest\hdt2. +pl line 15<br>

BUT WHY DOES print screw up on $args->{fh} ????


Example #3 shows the work around I've been using.
EXAMPLE #3
use strict; MAIN: { my $args = {}; open($args->{fh}, ">hdt.html") or die("Unable to open output file! +"); my $title = 'MY TTILE'; my $fh = $args->{fh}; print $fh <<EOF; <html> <head> <title>$title</title> </head> <body> Blah, Blah... </body> </html> EOF close $fh; }
This is not a major issue, but I've tried:
print ($args->{fh}) <<EOF; print +$args->{fh} <<EOF; print +($args->{fh}) <<EOF;
And nothing results in differing errors. The behavior here is consistent using either UNIX & Win32 Perls. TIA, MJD

Replies are listed 'Best First'.
Re: FileHandles as members of anon hash & Here docs???
by runrig (Abbot) on Jun 01, 2005 at 22:53 UTC
    See 'perldoc -f print', and see that if you want to use an array or other expression as a filehandle, you need to use a block:
    print {$args->{fh}} <<EOF;
      Ahhh, the "Block as an Expression" perlism. Shoulda guessed. Thanks to ALL ...
      MJD
Re: FileHandles as members of anon hash & Here docs???
by cmeyer (Pilgrim) on Jun 01, 2005 at 22:58 UTC