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

I would like to print to a file like so:
print FILE <<UNTIL_I_SAY_STOP; blah, blah, blah UNTIL_I_SAY_STOP
and die if I cant (supposing Ive reached my disk quota or something). Im familiar with print "this" || die, but how do you die when printing in this fashion?

Replies are listed 'Best First'.
Re: print or die
by lhoward (Vicar) on Jul 02, 2001 at 23:14 UTC
    When dealing w/ a heredoc string you put your "or die" w/ the original print statment:
    print FILE <<UNTIL_I_SAY_STOP or die "ERROR Writing to FILE: $!"; blah, blah, blah UNTIL_I_SAY_STOP
    It works similarly whenever you want to do something else after the heredoc...
    my $sub=substr(<<EOT,3,3); abc123def EOT print "sub=\"$sub\"\n";
    prints out 123.

    You can even get fancy (or hard to read depending on your preference) and use multiple heredocs in the same call:

    print <<EOT1,<<EOT2; foo EOT1 bar EOT2
Re: print or die
by Abigail (Deacon) on Jul 03, 2001 at 01:51 UTC
    It was already pointed out you can do:
    print FILE <<EOF or die $!; blah, blah EOF
    but that isn't enough. You should check the return value of close as well, because not every print will cause a flush. close will flush the buffer, and that might cause a disk quota exceeded event to happen.

    -- Abigail

Re: print or die
by Zaxo (Archbishop) on Jul 02, 2001 at 23:12 UTC

    How about:

    eval {print FILE <<UNTIL_I_SAY_STOP; blah, blah, blah UNTIL_I_SAY_STOP }; $@ && die "$@";

    That assumes $|=1;. If autoflush is not on you'll see errors on close rather than after print.

    After Compline,
    Zaxo

Re: print or die
by thabenksta (Pilgrim) on Jul 02, 2001 at 23:03 UTC

    You might find the answer here.

    -thabenksta
    my $name = 'Ben Kittrell'; $name=~s/^(.+)\s(.).+$/\L$1$2/g; my $nick = 'tha' . $name . 'sta';
Re: print or die
by sierrathedog04 (Hermit) on Jul 02, 2001 at 23:35 UTC
    use strict; # Tested on NT 4 Workstation, ActiveState 5.6.1 open (MYFILE, ">tempo4.txt") || die "Unable to open tempo4.txt"; my $myHereDoc =<<UNTIL_I_SAY_STOP; blah, blah, blah UNTIL_I_SAY_STOP if (print MYFILE $myHereDoc) { close MYFILE || die "unable to flush or close file"; } else { die "unable to print to file"; }
    Update: Revised so as to print to a file and then flush the output buffer.