in reply to Heredoc Inconsistency: Bareword Filehandle vs Lexical Filehandle

$ cat 11144614.pl #!/usr/bin/env perl use warnings; use strict; my $hfile = 'foo.txt'; # GOOD open(HFILE, '>', $hfile) or die "$hfile: $!"; print HFILE << "#EOT"; #Usage: foo.pl #EOT # BAD open(my $HFILE, '>', $hfile) or die "$hfile: $!"; print $HFILE << "#EOT"; #Usage: foo.pl #EOT # GOOD open($HFILE, '>', $hfile) or die "$hfile: $!"; print {$HFILE} << "#EOT"; #Usage: foo.pl #EOT $ perl 11144614.pl Argument "#EOT" isn't numeric in left bitshift (<<) at 11144614.pl lin +e 15. 10294240 $ perl -MO=Deparse,-p 11144614.pl use warnings; use strict; (my $hfile = 'foo.txt'); (open(HFILE, '>', $hfile) or die("${hfile}: $!")); print(HFILE "#Usage: foo.pl\n"); (open(my $HFILE, '>', $hfile) or die("${hfile}: $!")); print(($HFILE << '#EOT')); (open($HFILE, '>', $hfile) or die("${hfile}: $!")); print({$HFILE;} "#Usage: foo.pl\n"); 11144614.pl syntax OK

Indirect Object Syntax strikes again... and from print:

NOTE: If FILEHANDLE is a variable and the next token is a term, it may be misinterpreted as an operator unless you interpose a + or put parentheses around the arguments.

Update: -MO=Deparse,-p makes it even more obvious.

Replies are listed 'Best First'.
Re^2: Heredoc Inconsistency: Bareword Filehandle vs Lexical Filehandle
by LanX (Saint) on Jun 09, 2022 at 20:35 UTC
    In such a case I'd rather prefer direct object syntax.

    C:\tmp>perl use warnings; use strict; my $hfile = 'foo.txt'; my $HFILE; # GOOD open($HFILE, '>', $hfile) or die "$hfile: $!"; $HFILE->print(<< "#EOT"); #Usage: foo.pl #EOT __END__ C:\tmp>type foo.txt #Usage: foo.pl

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery