in reply to Writing to DATA

The DATA filehandle is just a an open handle on the current file. The current file is just the $0 variable (so long as you haven't changed it). So:

# main part of script ... # then redo the crc: rewrite_crc('datafile'); sub rewrite_crc { my $file = shift; open(SELF,"+<$0")||die $!; while(<SELF>){last if /^__END__/} print SELF new_crc($file),$/; truncate(SELF,tell SELF); close SELF; } sub new_crc { my $file = shift; my $crc = 0; # calculate new crc here $crc = 43256; return $crc; } __END__ 1234567

Replies are listed 'Best First'.
Re: Re: Writing to DATA
by bart (Canon) on Nov 15, 2003 at 07:31 UTC
    In my experience, at least on some platforms, truncate right after print may fail. You need an intermediate seek to be safe.
    print SELF new_crc($file),$/; seek SELF, 0, 1; truncate(SELF, tell SELF);
    See also perldoc -f seek:
    Due to the rules and rigors of ANSI C, on some systems you have to do a seek whenever you switch between reading and writing.

    Perhaps you don't need the truncate — or the seek. CRCs tend to all be the same string length.

Re: Re: Writing to DATA
by sweetblood (Prior) on Nov 14, 2003 at 17:30 UTC
    That's pretty darn clever, except that I think you meant to do the trucate prior to the print in rewrite_crc(), otherwise it prints the new crc then truncates it. But this is the basic idea I was looing for.

    What a great place our monestary is! Not to mention the fine people!

    Thanks and be well!

      No. The truncate call works fine where it is, the file will be truncated at its current position (after the write). Of course, you can truncate first and then write too.

        Huh!? I don't get anything after __END__ if the truncate is before the print. I wonder why it work for you but not I. I'm running on an HP-UX 11.i box, how 'bout you?