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

I'm trying to figure out why this works:
$stuff="0.4312342134234234"; $morestuff="0.2432134234342342"; open(F,'>'.'/tmp/foo1.txt'); printf(F << "__EOFOO__", $stuff, $morestuff); Some stuff: %.4f Some more stuff %.4f __EOFOO__ close(F);

and the same with a IO::File handle wont:

$stuff="0.4312342134234234"; $morestuff="0.2432134234342342"; $fh=IO::File->new(">/tmp/foo2.txt"); printf($fh << "__EOFOO__", $stuff, $morestuff); Some stuff: %.4f Some more stuff %.4f __EOFOO__
I'm trying to avoid having to detour over sprintf then use a normal print.

Replies are listed 'Best First'.
Re: IO::File handle and printf
by ambrus (Abbot) on Nov 03, 2010 at 13:56 UTC

    As an alternative to what Anon recommends above, you can try putting the handle in brackets:

    printf({ $fh } << "__EOFOO__", $stuff, $morestuff);

    The problem is that perl has to decide whether << starts a heredoc or means a left shift operator, and it guesses wrong in the case you show in your post.

    Update: parenthesis around the here-doc would also work:

    printf($fh (<< "__EOFOO__"), $stuff, $morestuff);
Re: IO::File handle and printf
by kcott (Archbishop) on Nov 03, 2010 at 14:58 UTC

    Or with less punctuation:

    use strict; use warnings; use IO::File; my $stuff = 0.4312342134234234; my $morestuff = 0.2432134234342342; my $fh = IO::File->new('io_heredoc_prob.out', 'w') or die $!; printf $fh <<'__EOFOO__', $stuff, $morestuff; Some stuff: %.4f Some more stuff %.4f __EOFOO__

    Output:

    $ cat io_heredoc_prob.out Some stuff: 0.4312 Some more stuff 0.2432

    -- Ken

Re: IO::File handle and printf
by Anonymous Monk on Nov 03, 2010 at 13:51 UTC
    Try without a space:

    printf($fh <<"__EOFOO__", $stuff, $morestuff); ^^
      I tried this:
      #!/usr/bin/perl use IO::File; $stuff="0.4312342134234234"; $morestuff="0.2432134234342342"; $fh=IO::File->new(">/tmp/foo2.txt"); $fh=sprintf($fh <<"__EOFOO__", $stuff, $morestuff); Some stuff: %.4f Some more stuff %.4f __EOFOO__
      But I get:
      Missing comma after first argument to sprintf function at test.pl line + 12, near "$morestuff)" (Might be a runaway multi-line << string starting on line 9) Execution of test.pl aborted due to compilation errors.
        sprintf doesn't take a file handle as first argument.

        PS, I think you wanted to avoid having to detour over sprintf... ;-)

        The sprintf can't work, sorry, that slipped in. What I meant to show was:
        $fh=IO::File->new(">/tmp/foo2.txt"); printf($fh <<"__EOFOO__", $stuff, $morestuff); Some stuff: %.4f Some more stuff %.4f __EOFOO__
        As someone else pointed out, {} arround $fh will work.