develooper Front page | perl.perl5.porters | Postings from November 2008

Re: [perl #1154] -pi doesn't sanely handle write errors

Thread Previous | Thread Next
From:
Chip Salzenberg
Date:
November 26, 2008 17:28
Subject:
Re: [perl #1154] -pi doesn't sanely handle write errors
Message ID:
20081127012753.GB17663@tytlal.topaz.cx
On Tue, Nov 18, 2008 at 01:11:27PM +0000, Ben Morrow wrote:
> 
> Quoth Mordechai.T.Abzug@nasa.gov (Morty Abzug):
> > On Mon, Nov 17, 2008 at 10:38:05AM -0800, Chip Salzenberg via RT wrote:
> > > As for restoring the partially read file back to its original name
> > > on error: I actually think that's a bad idea.  There may be a LOT of
> > > processing involved, and partial output is definitely better than no
> > > output in some circumstances.
> > 
> > In my use case, I was looking to use Perl to in-place edit system
> > configs.  The processing is minimal.  I would much rather that failure
> > automatically revert the config rather than leave a corrupt config
> > (neither the old nor the new) in place.
> 
>     perl -pi~ -e'... END { $? and rename "$ARGV~", $ARGV }'

That's a clever idiom that will work in many cases.  Kinda ugly, but oh
well.  I wonder if we already ensure that $ARGV is undef after the entire
while (<>) {} loop is complete.  If not, we should.  Otherwise a die or
nonzero exit or setting of $? in another END block could trigger a spurious
rename.  If we do appropriately unset $ARGV, then:

     perl -pi~ -e'... END { $? and $ARGV and rename "$ARGV~", $ARGV }'

I wonder whether we could make this a standard but optional feature of
inplace editing.  How about:

    ${^INPLACE_SAFE}++;   # nop in old Perls, forces rename on error in new Perls


> > And what about the case where one has an error when using -i without a
> > backup [...]
> 
> But that's not easy, since the original file has been unlinked and Unix
> doesn't have a 'flink' syscall. [...]  Just use a backup if you need to
> recover from errors.

Indeed.
-- 
Chip Salzenberg   twitter:chipsalz
"UTOPIA PLANITIA IS IN ORBIT is the new HAN SHOT FIRST" - Crisper Than Thou

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About