Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

questions regarding "+<"

by lightoverhead (Pilgrim)
on May 15, 2014 at 19:27 UTC ( #1086192=perlquestion: print w/replies, xml ) Need Help??
lightoverhead has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks

To my understanding "+<" will not clobber the contents of file when you try to write sth to it.

but...

#!/usr/bin/perl -w use strict; open (F, "+<",$ARGV[0]); my $out = ""; while(<F>){ chomp; $out .= $_."\tadd sth\n" if($.%2 == 0); } seek(F,0,0); print F $out; close(F);

I was expecting to insert the $out contents at the beginning of the file.

But it just removes the old contents of the file and prints the $out contents instead.

Does anyone have insight on this? Thank you!

Replies are listed 'Best First'.
Re: questions regarding "+<"
by choroba (Bishop) on May 15, 2014 at 19:42 UTC
    Works for me:
    $ echo qqqqq > 1 $ perl -E 'open my $F, "+<", "1" or die $!; print {$F} "w";' $ cat 1 wqqqq
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      choroba,

      Thank you for your reply.

      But your case actually proved my point of view:

      your file "1" originally contains 5 'q' ('qqqqq'),after your program, it only left 4 'q' ('wqqqq').

      this shows that the first 'q' was clobbered.

        Filesystems generally don't support an insert feature. "+<" gives you read/write access. It isn't a "prepend" or "insert" feature. Any changes made will write over what was there before, beginning at the current position within the file.

        If you want to prepend something to a file, the standard idiom is to rename the input file, create a new file by the original name of the input file, start copying the old (newly renamed) input file over to the new file, while adding your "insert" text at the appropriate point, and follow that insertion with a copy of the remainder of the source file. Then unlink the original source file. That's essentially what the -i Perl command line switch does.


        Dave

        Try the same with the ">" mode to see what clobbering means.
        لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1086192]
Front-paged by GotToBTru
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2017-11-19 07:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    In order to be able to say "I know Perl", you must have:













    Results (278 votes). Check out past polls.

    Notices?